believesInSanta believesInSanta - 6 months ago 37
Javascript Question

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

I am new to websockets.

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

I make a

object, set up its
callback and call its
method to test.

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

w.onmessage = (msg) => {

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
callback never fires.

Am I missing or misunderstanding anything?

EDIT: Ran across comparison vs., claims websocket implementation does not support pong. This may be the confirmation of it.

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


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.