如何在发送消息后保持 WebSocket 连接处于 OPEN 状态?

huangapple go评论95阅读模式
英文:

How to keep a websocket connection in OPEN readystate after send?

问题

我对Websockets还不太熟悉。

在我的设置中,我有一个用Go编写的简单的Websocket服务器(playground)。

我创建了一个WebSocket对象,设置了它的onmessage回调函数,并调用了它的send方法进行测试。

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

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

w.onopen = () => {
   w.send("Hello")  // 这个发送成功了
}

根据服务器代码,我期望接收到"Hello"消息,并每1.5秒向客户端发送"yahoo"。但实际上只发送了"Hello",没有发送任何"yahoo"。似乎WebSocket的readystate在某个时刻变为3(CLOSED)。

为了澄清,服务器接收并打印了"Hello",然后每1.5秒实际上发送了"yahoo"消息,但连接在那时已经关闭,所以onmessage回调函数从未触发。

我是否遗漏或误解了什么?

编辑:我看到了gorilla和golang.org/x/net的比较,声称golang.org/x/net的WebSocket实现不支持pong。这可能是对此的确认。

编辑:golang.org/x/net/websocket包在处理程序ServeHTTP函数返回时关闭WebSocket连接。默认情况下,WebSocket连接与处理程序的实例绑定在一起。

英文:

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

得分: 1

当处理程序函数返回时,在您的情况下,即EchoServer,套接字将由HTTP框架自动关闭。
由于您为循环写入yahoo响应到客户端启动了一个go例程,EchoServer函数将在发送响应之前终止(从而关闭套接字)。

解决方案是删除go例程的生成,只需在EchoServer内部执行循环即可。

英文:

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.

huangapple
  • 本文由 发表于 2016年11月21日 07:12:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/40710545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定