简体   繁体   中英

Correct way to handle Websocket

I've a client to server Websocket connection which should be there for 40 seconds or so. Ideally it should be forever open.

The client continually sends data to server and vice-versa.

Right now I'm using this sequence:

var socket;
function senddata(data)
{

    if (!socket)
    {
        socket = new WebSocket(url);
        socket.onopen = function (evt) {

            socket.send(data);

            socket.onmessage = function (evt) {
                var obj = JSON.parse(evt.data);

                port.postMessage(obj);
            }

            socket.oneerror = function (evt) {
                socket.close();
                socket = null;
            }
           socket.onclose = function(evt){
               socket = null;
           }


        }
    }
    else
    {
        socket.send(data);
    }

}

Clearly as per current logic, in case of error, the current request data may not be sent at all.

To be frank it sometimes gives error that websocket is still in connecting state. This connection breaks often due to networking issues. In short it does not work perfectly well.

I've read a better design : How to wait for a WebSocket's readyState to change but does not cover all cases I need to handle.

Also I've Googled about this but could not get the correct procedure for this.

So what is the right way to send regular data through Websockets which handles well these issues like connection break etc?

An event you don't seem to cover is onclose. Which should work really well, since it's called whenever the connection terminates. This is more reliable than onerror, because not all connection disruptions result in an error.

I personally use Socket.IO , it enables real-time bidirectional event-based communication between client and server.

It is event driven. Events such as

on connection :: socket.on('conection',callback);

and

on disconnect :: socket.on('disconnect',callback);

are built in with socket.io so it can help you with your connection concerns. Pretty much very easy to use, check out their site if you are interested.

I use two-layer scheme on client: abstract-wrapper + websocket-client:

The responsibilities of the websocket-client are interacting with a server, recovering the connection and providing interfaces (event-emitter and some methods) to abstract-wrapper.

The abstract-wrapper is a high-level layer, which interacts with websocket-client, subscribes to its events and aggregating data , when the connection is temporary failed. The abstract-wrapper can provide to application layer any interface such as Promise, EventEmitter and so on.

On application layer, I just work with abstract-wrapper and don't worry about connection or data losing. Undoubtedly, it's a good idea to have here information about the status of connection and data sending confirmation, because it's useful.

If it is necessary, I can provide some code for example

This apparently is a server issue not a problem in the client.

I don't know how the server looks like here. But this was a huge problem for me in the past when I was working on a websocket based project. The connection would continuously break.

So I created a websocket server in java, and that resolved my problem.

websockets depend on lots of settings, like if you're using servlets then servlet container's settings matter, if you're using some php etc, apache and php settings matter, for example if you create a websocket server in php and php has default time-out of 30 seconds, it will break after 30 seconds. If keep-alive is not set, the connection wont stay alive etc.

What you can do as quick solution is

  1. keep sending pings to a server after a certain amount of time (like 2 or 3 seconds, so that if a websocket is disconnected it is known to the client so it could invoke onclose or ondisconnect, I hope you know that there is no way to find if a connection is broken other than failing to send something.
  2. check server's keep-alive header
  3. If you have access to server, then it's timeouts etc.

I think that would help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM