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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办