简体   繁体   中英

Socket exceptions in node.js

I keep getting two exceptions on my server that close the process even though the entire script is wrapped in a try catch block. The exceptions are:

events.js:160
throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at exports._errnoException (util.js:1022:11)
    at WriteWrap.afterWrite [as oncomplete] (net.js:804:14)

and

Error: invalid opcode: 7
    at Receiver.start (/home/mysite/public_html/node_modules/ws/lib/Receiver.js:211:18)
    at Receiver.add (/home/mysite/public_html/node_modules/ws/lib/Receiver.js:134:14)
    at Socket._ultron.on (/home/mysite/public_html/node_modules/ws/lib/WebSocket.js:139:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:551:20)

From the sockets lib.

Does anyone know what is causing this and how to prevent it?

edit:

An excerpt:

try
{
    wss.broadcast = function broadcast(data) {
      wss.clients.forEach(function (client) {
        if (client.readyState == WebSocket.OPEN) {
          client.send(data);
        }
      });
    };


    wss.on("connection", function (ws)
    {
        if(blacklist.indexOf(GetClientIP(ws)) != -1)
        {
            console.log("Kicking banned");
            ws.close();
            return;
        }

        clientCount++;

        wss.broadcast(welcomeMessage);


        ws.on("message", function (message)
        {
            ProcessMessage(message);
        });

        ws.on("close", function ()
        {
            clientCount--;

            wss.broadcast(goodbyeMessage);
        });
    });
}
catch(exxx)
{
    console.log("Caught a exception);

    console.log(exxx);
}

Attach an error handler to your websocket to catch errors:

wss.on("connection", function (ws) {
  ...

  ws.on('error', function(err) {
    console.log('Websocket error!: ' + err);
  });

  ...
});

This prevents Node.js from crashing when you get an error like EPIPE.

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