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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?