How to deal with 'read ETIMEDOUT' in Node.js?

Problem

I have a pub/sub model using Node.js to transmit data from one client to another client. Besides, server also records everything received and send to new clients.

However, some data corrupted when transfer, and I got error like:

Error with socket!
{ [Error: write EPIPE] code: 'EPIPE', errno: 'EPIPE', syscall: 'write' }
Error with socket!
{ [Error: read ETIMEDOUT] code: 'ETIMEDOUT', errno: 'ETIMEDOUT', syscall: 'read' }

I don't know how to properly handle these errors. It looks like client is down.

Since the server is only a proxy like server, it doesn't really know what data means. I have no idea how to validate every data pack before meet these errors.

Here is my code:

// server is an object inheriting from net.Server
server.on('listening', function() {
    var port = server.address().port;
}).on('connection', function(cli) {
    cli.socketBuf = new Buffers();
    cli.commandStarted = false;
    cli.dataSize = 0;
    cli.setKeepAlive(true, 10*1000);
    cli.setNoDelay(true);
    cli.on('connect', function() {
        server.clients.push(cli);
    }).on('close', function() {
        var index = server.clients.indexOf(cli);
        server.clients.splice(index, 1);
    }).on('data', function (buf) {
        server.emit('data', cli, buf);
        if(op.autoBroadcast) {
            _.each(server.clients, function(c) {
                if(c != cli) c.write(buf);
            });
        }
    }).on('error', function(err) {
        console.log('Error with socket!');
        console.log(err);
    });
}).on('error', function(err) {
    console.log('Error with server!');
    console.log(err);
});

// ...

// room.dataSocket is an instance of server beyond
room.dataSocket.on('data', function(cli, d) {
    // bf is a buffered file
    bf.append(d);
    room.dataFileSize += d.length;

}).on('connection', function(con){
    bf.readAll(function(da) {
        con.write(da);
    });
});
Problem courtesy of: liuyanghejerry

Solution

If you get an EPIPE or indeed any error when writing, the peer has closed or the connection has been dropped. So you must close the connection at that point.

If you get a read timeout the inference is that either you have set an unrealistically short timeout or else the peer has failed to deliver in time: in the second case once again you should assume the connection is down, and close it.

Solution courtesy of: EJP

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.