Ws: how to determine if ws is already open

Created on 23 Dec 2016  路  3Comments  路  Source: websockets/ws

    ws.on('open', function open() {
            console.log('client is opened');
            ws.send(JSON.stringify({
                uuid: uuid,
                key: key,
                lock: true
            }));
        });

can we do a check if ws is opened?

something like:

if(ws.isOpen){
 ws.send('foo');
}
else{
    ws.on('open', function open() {
            console.log('client is opened');
            ws.send('foo'));
        });
}

Most helpful comment

You can check the readyState.

if (ws.readyState === WebSocket.OPEN) {
  ...
} 

All 3 comments

You can check the readyState.

if (ws.readyState === WebSocket.OPEN) {
  ...
} 

thanks!

What I did for now, I put this in the top of my code:

js ws.once('open', function open() { ws.isOpen = true; });

:) but thanks, I will probably do it the more canonical way

Closing this, please comment or reopen if needed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ImBundle picture ImBundle  路  3Comments

binarykitchen picture binarykitchen  路  5Comments

jorenvandeweyer picture jorenvandeweyer  路  4Comments

sherikapotein picture sherikapotein  路  3Comments

Globik picture Globik  路  3Comments