在Go的WebSocket服务器上获取JSON数据。

huangapple go评论105阅读模式
英文:

Get json data on go websocket server

问题

当我从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}

一切正常工作。

英文:

When I send from js client socket.send(&#39;{&quot;text&quot;:&quot;111&quot;}&#39;) and get this on server, by websocket.JSON.Receive(ws, &amp;data), data remain empty. I use "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 &lt;- &amp;NewClientEvent{clientKey, msgChan}
	defer func(){ clientDisconnects &lt;- clientKey}()

	go func(){
		for msg := range msgChan{
			ws.Write([]byte(msg.text))
		}
	}()
	for {
		var data Item
   		err := websocket.JSON.Receive(ws, &amp;data)
		if err != nil {
			log.Println(&quot;Error: &quot;, err.Error())
			return
		}
		messages &lt;- &amp;Msg{clientKey, data.text}
	}
}

But if I try send socket.send(&#39;&quot;text&quot;&#39;) and get it by this:

var data string
err := websocket.JSON.Receive(ws, &amp;data)
    		if err != nil {
    			log.Println(&quot;Error: &quot;, err.Error())
    			return
    		}
    		messages &lt;- &amp;Msg{clientKey, data}

everything is working.

答案1

得分: 5

很可能你需要在使用JSON.receive之前定义你的结构体,例如:

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

英文:

Chances are you'll need to define your struct before you can use JSON.receive on an object like

{ &quot;text&quot;: &quot;Hi&quot; }

type socketData struct {
    Text string `json:&quot;text&quot;`
}

Then

data := &amp;socketData{}

websocket.JSON.receive(ws, &amp;data)

log.Println(data.Text) // Hi

If you're going to be sending random data that you can't really define a struct for (though this is the preferred way of doing it) you can just declare an interface{}

var data map[string]interface{}

log.Println(data[&quot;text&quot;].(string)) // Hi

http://play.golang.org/p/Jp5qKtiUGw

huangapple
  • 本文由 发表于 2016年2月29日 09:37:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/35690624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定