node.js websocket crashes when client disconnect

前端 未结 3 1300
执念已碎
执念已碎 2021-02-10 16:11

I am very new to NodeJS and Websockets, but i am trying to play with it.

What i do is read incoming datas from Serial port, then send these dat

相关标签:
3条回答
  • 2021-02-10 16:30

    I think, you should remove the socket from your CLIENTS array on both close and error event. Otherwise it tries to send a message to a socket that is closed.

    0 讨论(0)
  • 2021-02-10 16:41

    Try this while sending data to client: - socket is my current web socket object.It overwrites the default >WebSocket.js class condition that throws "not-opened error".

    if (socket.readyState != socket.OPEN) {
        console.error('Client state is ' + socket.readyState);
        //or any message you want
    } else {
        socket.send(JSON.stringify(object)); //send data to client
    }
    
    0 讨论(0)
  • 2021-02-10 16:45

    I was having this same issue. Turned out I was attempting to send events to sockets that were in the "closing" state. Checking that each socket was specifically open before broadcasting a message fixed it for me:

        function sendAll(data){
            for(var i = 0; i < clients.length; i++){
                if(this.clients[i].readyState != this.clients[0].OPEN){
                    console.error('Client state is ' + this.clients[i].readyState);
                }
                else{
                    this.clients[i].send(data);
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题