我正在尝试为GlassFish实现一个websocket代理服务器。如果我尝试连接多个客户端,我会得到错误:
ReadMessage Failed: websocket: close 1007 Illegal UTF-8 Sequence.
我确信GlassFish服务器发送正确的数据,因为相同的服务器与另一个使用node.js实现的代理服务器正常工作。
func GlassFishHandler(conn *websocket.Conn){
defer conn.Close()
conn.SetReadDeadline(time.Now().Add(1000 * time.Second))
conn.SetWriteDeadline(time.Now().Add(1000 * time.Second))
fmt.Println("WS-GOLANG PROXY SERVER: Connected to GlassFish")
for {
messageType, reader, err := conn.NextReader()
if err != nil {
fmt.Println("ReadMessage Failed: ", err) // <- error here
} else {
message, err := ioutil.ReadAll(reader)
if (err == nil && messageType == websocket.TextMessage){
var dat map[string]interface{}
if err := json.Unmarshal(message, &dat); err != nil {
panic(err)
}
// get client destination id
clientId := dat["target"].(string)
fmt.Println("Msg from GlassFish for Client: ", dat);
// pass through
clients[clientId].WriteMessage(websocket.TextMessage, message)
}
}
}
}
总结我的评论作为一个答案:
当你写客户端时,你从GlassFish消息中获取clientId,从map中获取客户端,然后写到它-基本上是clients[clientId].WriteMessage(...)
。
虽然您的map访问可以是线程安全的,但写入不是,因为这可以看作是:
// map access - can be safe if you're using a concurrent map
client := clients[clientId]
// writing to a client, not protected at all
client.WriteMessage(...)
所以可能发生的是两个独立的例程同时写同一个客户端。您应该通过在WriteMessage
方法实现中添加互斥锁来保护您的客户机。
顺便说一句,实际上不是用互斥锁来保护这个方法,一个更好的,更"go-ish"的方法是使用一个通道来写消息,每个客户端使用一个从通道中消费并写到实际套接字的例程。
在client结构体中,我要这样做:
type message struct {
msgtype string
msg string
}
type client struct {
...
msgqueue chan *message
}
func (c *client)WriteMessage(messageType, messageText string) {
// I'm simplifying here, but you get the idea
c.msgqueue <- &message{msgtype: messageType, msg: messageText}
}
func (c *client)writeLoop() {
go func() {
for msg := ragne c.msgqueue {
c.actuallyWriteMessage(msg)
}
}()
}
,当创建新的客户端实例时,只需启动写循环