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

人走茶凉 提交于 2019-12-23 01:10:29

问题


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);
    });
});

回答1:


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.



来源:https://stackoverflow.com/questions/14972106/how-to-deal-with-read-etimedout-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!