Node.js websocket-server crashes when client closes tab

I got a little example-project running with a node.js Server which is used to broadcast to clients.

The Server handling the sockets (from this guy ):

var ws = require('');
var url = require("url");
var http = require('http').createServer(onRequest).listen(3000);
var clients = [];
var server = ws.attach(http, { path: '/mywebsocket' });

server.on('connection', function (socket) {
    console.log('new client');
    socket.on('message', function (msg) {
        console.log("msg recv: " + JSON.stringify(msg));
    socket.on('close', function () {
        console.log('client leaving ');
        clients.splice(clients.indexOf(this), 1);

function onRequest(request, response) {
    var urlobj = url.parse(request.url, true);
    if (urlobj.query.activity) {
        var actObj = JSON.parse(urlobj.query.activity);
        if (actObj) {
            clients.forEach(function(client) {
                var msg = JSON.stringify(actObj);
                console.log("NODE sending " + msg);

The small sample-page:

<script type="text/javascript">
    var node_ws = new WebSocket("ws://" + "localhost" + ":" + "3000" + "/mywebsocket");

    node_ws.onmessage = function (evt) {
        var msg = JSON.parse(;
        var action = msg.action;

        var para = document.createElement("p");
        var node = document.createTextNode(action);

        var element = document.getElementById("div1");

<div id="div1">Test</div>

The Setup works fine, pushing Data to the Client and showing it on the website. When the client leaves by clicking on another link the Server just notes that a client left. When the client leaves by closing the Tab in Browser (in this case Chrome) the Server running on Node.js crashes with the following Error message:

throw er; // Unhandled 'error' event
Error: read ECONNRESET
at exports.errnoException (util.js:860:11)
at TCP.onread (net.js:544:26)

I tried catching the event of closing with onbeforeunload and closing the clients Websocket, but without success. The

I can't imagine I am the only one having this issue, but I didn't find this exact behavior anywhere else.

Any help is appreciated!


I had the same problem.

This was my solution. I put it below the socket on close function:

socket.on('error', function () {        
    //Close the socket

I don't know if the socket needs to be removed here as the socket close stuff seems to handle it, but I put the code in for removing it anyway just in case.

Need Your Help

FIFO in MySQL db

mysql fifo inventory

I'm using Mysql (not MSSQL) database and bumped onto a problem I seem to be unable to solve. I would very much appreciate your help finding a solution.

Printing named tuples

python namedtuple

In Python 2.7.1 I can create a named tuple: