Пример #1
0
func wsserver(ws *websocket.Conn) {

	// read msg
	var (
		msg msgproto.Msg
		err error
		id  int32
		// topic string
	)
	for {
		err = msgCodec.Receive(ws, &msg)
		checkErr("Receive", err)
		if err != nil {
			break
		}
		// add client and topic client
		id = msg.GetId()
		if _, ok := clients[id]; !ok {
			clients[id] = ws
		}

		handleMsg(msg, ws)
	}

	defer func() {
		delete(clients, id)
		ws.Close()
	}()
}
Пример #2
0
func handleMsg(msg msgproto.Msg, ws *websocket.Conn) {
	log.Printf("msg received : id : %d, type : %d \n", msg.GetId(), msg.GetType())
	switch MsgType(msg.GetType()) {
	case LOGIN:
		// send all clients
		var msgcontent = "clients: \n"
		for key, _ := range clients {
			msgcontent += strconv.Itoa(int(key)) + "\n"
		}
		// pbMsg := &msgproto.Msg{
		// 	Id:      proto.Int32(msg.GetId()),
		// 	Topic:   proto.String(msg.GetTopic()),
		// 	Content: proto.String(msgcontent),
		// 	Type:    proto.Int32(msg.GetType()),
		// }
		pbMsg := PbMsgFactory(msg.GetId(), msg.GetTopic(), msgcontent, msg.GetType())

		err := msgCodec.Send(ws, pbMsg)
		checkErr("Send at LOGIN in handleMsg", err)
		log.Printf("Login send : %s %v\n", msgcontent, clients)
	case CONNECT:
		pbMsg := PbMsgFactory(msg.GetId(), msg.GetTopic(), "connected, start to talk", msg.GetType())

		err := msgCodec.Send(ws, pbMsg)
		checkErr("Send at CONNECT in handleMsg", err)
	case MSG_CONTENT:
		// here topic is another id
		id, err := strconv.Atoi(msg.GetTopic())
		checkErr("Atoi at MSG_CONTENT case of handleMsg", err)
		// find the client in the clients and send the data
		// proto no setter,just get
		toClient := clients[int32(id)]
		// pbMsg := &msgproto.Msg{
		// 	Id:      proto.Int32(int32(id)),
		// 	Topic:   proto.String(strconv.Itoa(int(msg.GetId()))),
		// 	Content: proto.String(msg.GetContent()),
		// 	Type:    proto.Int32(msg.GetType()),
		// }
		pbMsg := PbMsgFactory(int32(id), strconv.Itoa(int(msg.GetId())), msg.GetContent(), msg.GetType())

		err = msgCodec.Send(toClient, pbMsg)
		checkErr("Send at MSG_CONTENT case of handleMsg", err)
	case MSG_CHATROOM:
		topic := msg.GetTopic()
		if v, ok := topicclients[topic]; ok {
			// if not exists
			if _, ok := v[ws]; !ok {
				// add
				v[ws] = true
			}

		} else {
			topicclients[topic] = map[*websocket.Conn]bool{ws: true}
		}

		// check topic exist or not
		if v, ok := topicclients[topic]; ok {
			for c, _ := range v {

				err := msgCodec.Send(c, &msg)
				checkErr("Send at MSG_CHATROOM case of handleMsg", err)
			}

		} else {
			pbMsg := PbMsgFactory(int32(msg.GetId()), strconv.Itoa(int(msg.GetId())), "chatroom doesn't exist", msg.GetType())
			err := msgCodec.Send(clients[msg.GetId()], pbMsg)
			checkErr("Send at MSG_CHATROOM case of handleMsg", err)
		}
		fmt.Println("topicclients : ", topicclients)
		// send back msg
	default:
		log.Printf("msg type not supported : %d \n", msg.GetType())
	}

}