Node.js 使用UDP传输文件
Node.js file transfer using UDP
我正在尝试创建一个简单的 Node.js 服务器,它通过 UDP 从客户端接收文件。我遇到的问题是,每次我尝试传输大文件(任何超过 100kb 的文件)时,服务器似乎都没有响应。到目前为止,我已经成功地传输了最大 50kb 的文件。
有什么办法可以解决这个问题吗?
客户代码:
var PORT = 33333;
var HOST = 'localhost';
var dgram = require('dgram');
var log = require('sys').log;
var client = dgram.createSocket('udp4');
var fs = require("fs");
fs.readFile('C:\test.pdf', function (err,data) {
if (err) {
return console.log(err);
}
client.send(data, 0, data.length, PORT, HOST, function(err, bytes) {
if (err)
throw err;
log('UDP file sent to ' + HOST +':'+ PORT);
log('File sise: ' + data.length);
});
});
服务器代码:
var PORT = 33333;
var HOST = 'localhost';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var fs = require("fs");
var log = require('sys').log;
var wstream = fs.createWriteStream('test.pdf');
wstream.on('finish', function () {
console.log('file has been written');
});
server.on('message', function (message, remote) {
wstream.write(message);
wstream.end();
});
server.bind(PORT, HOST);
来自 dgram
文档:
The Payload Length field is 16 bits wide, which means that a normal payload cannot be larger than 64K octets including internet header and data (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); this is generally true for loopback interfaces, but such long datagrams are impractical for most hosts and networks.
您不能发送超过 65,507 字节的数据报。这是 UDP 的硬性限制。听起来您应该为这些文件使用更高级别的协议。
我正在尝试创建一个简单的 Node.js 服务器,它通过 UDP 从客户端接收文件。我遇到的问题是,每次我尝试传输大文件(任何超过 100kb 的文件)时,服务器似乎都没有响应。到目前为止,我已经成功地传输了最大 50kb 的文件。
有什么办法可以解决这个问题吗?
客户代码:
var PORT = 33333;
var HOST = 'localhost';
var dgram = require('dgram');
var log = require('sys').log;
var client = dgram.createSocket('udp4');
var fs = require("fs");
fs.readFile('C:\test.pdf', function (err,data) {
if (err) {
return console.log(err);
}
client.send(data, 0, data.length, PORT, HOST, function(err, bytes) {
if (err)
throw err;
log('UDP file sent to ' + HOST +':'+ PORT);
log('File sise: ' + data.length);
});
});
服务器代码:
var PORT = 33333;
var HOST = 'localhost';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var fs = require("fs");
var log = require('sys').log;
var wstream = fs.createWriteStream('test.pdf');
wstream.on('finish', function () {
console.log('file has been written');
});
server.on('message', function (message, remote) {
wstream.write(message);
wstream.end();
});
server.bind(PORT, HOST);
来自 dgram
文档:
The Payload Length field is 16 bits wide, which means that a normal payload cannot be larger than 64K octets including internet header and data (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); this is generally true for loopback interfaces, but such long datagrams are impractical for most hosts and networks.
您不能发送超过 65,507 字节的数据报。这是 UDP 的硬性限制。听起来您应该为这些文件使用更高级别的协议。