duanhan4763 2016-11-20 23:12
浏览 395
已采纳

发送后如何保持Websocket连接处于OPEN就绪状态?

I am new to websockets.

In my setup I have a trivial websocket server written in Go (playground)

I make a WebSocket object, set up its onmessage callback and call its send method to test.

var w = new WebSocket("ws://localhost:12345/echo")

w.onmessage = (msg) => {
   console.log(msg.data)
}

w.onopen = () => {
   w.send("Hello")  // this fires OK
}

What I expect to happen based on the server code is to receive the "Hello" message and to keep sending "yahoo" every 1.5s to the client. What actually happens is "Hello" is sent, but none of the "yahoo"'s make it thru. It seems somewhere along the WebSocket.readystate becomes 3 (CLOSED).

To clarify, the server receives and prints "Hello" then actually fires a "yahoo" message every 1.5s, but the connection is closed by then so the onmessage callback never fires.

Am I missing or misunderstanding anything?

EDIT: Ran across comparison github.com/gorilla vs. golang.org/x/net, claims golang.org/x/net websocket implementation does not support pong. This may be the confirmation of it.

EDIT: Package golang.org/x/net/websocket closes the websocket connection when the handler ServeHTTP function returns. By default a websocket connection is tied to an instance of the handler.

  • 写回答

1条回答 默认 最新

  • doudi2431 2016-11-21 08:36
    关注

    When the handler function returns, in your case EchoServer the socket will be automatically closed by the http framework. Since you start a go routine for the loop writing the yahooresponse to the client the EchoServer function will terminate (and therefor closing the socket) before it has time to send a response.

    The solution is to remove the spawning of the go routine and just do the loop inside the EchoServer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵