Example #1
0
// handle websocket request
// TODO 1. map with manual rw lock
//      2. connection limit
//		3. validate connection info (ex. roomid, userid) if it needed,(at least to add roomid path in path)
func (rc RoomCenter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Println("recevie a connection")
	r.ParseForm()
	roomid := r.Form.Get("roomid")
	if len(roomid) == 0 {
		roomid = "1"
	}
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}
	hub, ok := rc.rooms[roomid]
	if !ok {
		hub = newHub(roomid)
		rc.lock.Lock()
		rc.rooms[roomid] = hub
		rc.lock.Unlock()
		go hub.run()
	}
	c := &connection{send: make(chan []byte, 256), ws: ws, h: hub}
	c.h.register <- c
	defer func() { c.h.unregister <- c }()
	go c.writer()
	c.reader()
	//c.writer()
}
Example #2
0
//TODO implement the logic
func (r *Router) DealMsg(m Msg, reply *string) (err error) {
	log.Println("recv post msg", m)
	conns, err := getConnectors(m.Roomid)
	if err != nil {
		log.Println("get connectors addrs error", err)
		return err
	}
	data, err := json.Marshal(m)
	if err != nil {
		log.Println(" json marshal error:%v", err)
		return err
	}
	b := &BroadcastInfo{Roomid: m.Roomid, Msg: data}
	log.Println("start rpc call connector broadcast", m)
	for _, connAddr := range conns {
		client, err := rpc_pool.GetRpcClient(connAddr)
		if err != nil {
			log.Println("get rpc client error", err)
			continue
		}
		err = client.Call("RoomCenter.Broadcast", b, &reply)
		if err != nil {
			log.Println("rpc broadcast error:", err)
			*reply = "error"
		}
		log.Println("rpc result", *reply)
	}
	*reply = "OK"
	return
}
Example #3
0
func (rc *RoomCenter) Broadcast(b *BroadcastInfo, reply *string) error {
	hub, ok := rc.rooms[b.Roomid]
	if !ok {
		*reply = "room not found"
		log.Println("room id not found")
		return errors.New(*reply)
	}
	hub.broadcast <- b.Msg
	*reply = "ok"
	return nil
}