如何处理 Node.js 中的“读取 ETIMEDOUT"? [英] How to deal with 'read ETIMEDOUT' in Node.js?

查看:122
本文介绍了如何处理 Node.js 中的“读取 ETIMEDOUT"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个发布/订阅模型,使用 Node.js 将数据从一个客户端传输到另一个客户端.此外,服务器还会记录收到的所有内容并将其发送给新客户端.

I have a pub/sub model using Node.js to transmit data from one client to another client. Besides, the server also records everything received and sends it 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 the client is down.

由于服务器只是一个类似于服务器的代理,它并不真正知道数据是什么意思.我不知道如何在遇到这些错误之前验证每个数据包.

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

这是我的代码:

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

推荐答案

如果在写入时出现 EPIPE 或确实出现任何错误,则表示对等方已关闭或连接已断开.所以你必须在那个时候关闭连接.

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.

这篇关于如何处理 Node.js 中的“读取 ETIMEDOUT"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆