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

anonaka picture anonaka  路  5Comments

NodePing picture NodePing  路  5Comments

ImBundle picture ImBundle  路  3Comments

bartosz-m picture bartosz-m  路  3Comments

makc picture makc  路  4Comments