buffer上传大文件时,client报错
发布于 7 年前 作者 wangning0 3583 次浏览 来自 问答

先贴出client和server的代码,node的版本号为v8.1.2

服务端代码:

// buffer_server.js

const fs = require('fs');
const http = require('http');
const zlib = require('zlib');

const server = http.createServer((req, res) => {
    let index = 0;
    req.on('data', function(chunk) {
        console.log(++index, chunk.length);
    });
    res.end('OK');
})

server.listen(3001, () => {
    console.log('started');
});

客户端代码:

// buffer_client.js
const fs = require('fs');
const http = require('http');
const zlib = require('zlib');
const path = require('path');

const filename = process.argv[2];
const server = process.argv[3];

const options = {
    port: 3001,
    hostname: server,
    method: 'PUT',
    protocol: 'http:',
    headers: {
        filename: path.basename(filename),
        'Content-Encoding': 'gzib'
    }
}

const req = http.request(options, (res) => {
    console.log('client done');
})
fs.readFile(filename, (err, buffer) => {
    console.log('获取文件完毕\n');
    console.log('开始压缩');
    zlib.gzip(buffer, (err, buffer) => {
        console.log('压缩完毕');
        console.log(buffer.length);  // 1336191186  1.2G左右的文件
        req.write(new Buffer(1336191186));
        req.end();
    })
})

req.on('error', (err) => {
    console.log(err);
    /**
     * 
     * 出现的错误: 
     * 
     * { Error: read ECONNRESET
        at exports._errnoException (util.js:1016:11)
        at TCP.onread (net.js:609:25) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
     */
})

req.on('data', (data) => {
    console.log(data, 'data');
})

```


问题是,在上传1.2GB左右的压缩文件,一次性去通过write去发送给server之后,client会报错,报错信息如下:

```
{ Error: read ECONNRESET
    at exports._errnoException (util.js:1016:11)
    at TCP.onread (net.js:609:25) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
```

我自己判定是因为一次性write的buffer数量太大造成的,求解具体原因 谢谢
2 回复

问题出在这里

// buffer_server.js
const server = http.createServer((req, res) => {
    let index = 0;
    req.on('data', function(chunk) {
        console.log(++index, chunk.length);
    });
    res.end('OK'); // <- 这里
})

接收到请求立刻就end了连接,自然无法继续接收数据而返回ECONNRESET 正确方式应该是等待所有数据上传完毕时结束连接

const server = http.createServer((req, res) => {
    let index = 0;
    req.on('data', function(chunk) {
        console.log(++index, chunk.length);
    });
    req.on('end', function() {
		res.end('OK');
	});
})

@dislido 啊!是的!实在是不好意思 犯了这么低级的错误 谢谢! 应该在数据接受完毕后的!谢谢

回到顶部