从websocket收到消息时,不会导致“ Websocket:关闭1011”

I'm trying to subscribe to an event from a client to a server. I can subscribe to the event using JavaScript but when I use Golang and the Gorilla Websocket library I get a

'websocket: close 1011 (internal server error)'

every time I start a read from the socket.

I tried using the /x/websocket library as well but when I tried to read from the socket I end up hanging and I dont get the '1011' error.

If I use this JavaScript code on my browser it works:

<html>
  <head>
  </head>
  <body>
    <script>
        var socket = new WebSocket("ws://blehip:blehpport");

        function send(data) {
            socket.send(JSON.stringify(data));
        }

        socket.onopen = function() {
            send({
                action: 'subscribe',
                auth_token: 'Bleh',
                request_id: 'Bleh',
                data: {
                    account_id: 'bleh',
                    binding: "bleh"
                }
            });
        }

        socket.onmessage = function(raw_message) {
            var json_data = JSON.parse(raw_message.data);

            console.log(json_data);
        };

    </script>
  </body>
</html>

I get a stream of JSON objects in real time.

This is my small Golang, Gorilla/Websockets script

func main() {
    var server = flag.String("server", "blehIP:BlehPort", "server address")

    var wg sync.WaitGroup
    flag.Parse()

    url := url.URL {
        Scheme: "ws",
        Host: *server,
        Path: "",
    }

    conn, _, err := websocket.DefaultDialer.Dial(url.String(), nil)
    if err != nil {
        log.Fatal("Dial Error: ", err)
    }
    defer conn.Close()

    payload := []byte(`{"action":"subscribe",`+
                       `"auth_token":"` + bleh + `",`+
                       `"request_id":"` + bleh + `",`+
                       `"data": {`+
                                `"account_id":"` + bleh + `",`+
                                `"binding":"` + bleh + `"}`+
                      `}`)

    wg.Add(1)
    go func() {
        defer conn.Close()
        defer wg.Done()

        err = conn.WriteMessage(websocket.TextMessage, payload)
        if err != nil {
            log.Println("Write Error: ", err)
            return
        }

        m := frame{}
        err := conn.ReadJSON(&m)
        if err != nil {
            log.Println("WebScoket closed.", err)
            return
        }


        // msg := string(bytes[:])
        fmt.Printf("%v", m)
    }()
    wg.Wait()

    return
}

The error returned is: WebSocket closed. websocket: close 1011 (internal server error)

dop82210
dop82210 你是对的。谢谢...谢谢
一年多之前 回复
dousuize3082
dousuize3082 Go程序看起来正确,但是您没有显示替换为有效负载的字符串。结果是否可能是无效的JSON?Javascript版本将正确地转义值。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐