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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。