当我从js客户端socket.send('{"text":"111"}')
发送并在服务器上获取此内容时,到websocket.JSON.Receive(ws, &data)
,数据仍为空。我使用"golang.org/x/net/websocket"
type (
Msg struct {
clientKey string
text string
}
NewClientEvent struct {
clientKey string
msgChan chan *Msg
}
Item struct {
text string
}
)
var (
clientRequests = make(chan *NewClientEvent, 100)
clientDisconnects = make(chan string, 100)
messages = make(chan *Msg, 100)
)
func ChatServer(ws *websocket.Conn) {
msgChan := make(chan *Msg, 100)
clientKey := time.Now().String()
clientRequests <- &NewClientEvent{clientKey, msgChan}
defer func(){ clientDisconnects <- clientKey}()
go func(){
for msg := range msgChan{
ws.Write([]byte(msg.text))
}
}()
for {
var data Item
err := websocket.JSON.Receive(ws, &data)
if err != nil {
log.Println("Error: ", err.Error())
return
}
messages <- &Msg{clientKey, data.text}
}
}
但是,如果我尝试发送socket.send('"text"')
并通过以下方式获取它:
var data string
err := websocket.JSON.Receive(ws, &data)
if err != nil {
log.Println("Error: ", err.Error())
return
}
messages <- &Msg{clientKey, data}
一切都在正常。
您可能需要
先定义结构,然后才能在对象上使用JSON.receive
,例如
{ "text": "Hi" }
type socketData struct {
Text string `json:"text"`
}
然后
data := &socketData{}
websocket.JSON.receive(ws, &data)
log.Println(data.Text) // Hi
如果您要发送无法真正定义结构的随机数据(尽管这是首选方法),您可以声明一个interface{}
var data map[string]interface{}
log.Println(data["text"].(string)) // Hi
http://play.golang.org/p/Jp5qKtiUGw