Tito Rahman
Tito Rahman

Reputation: 107

Node.js file transfer using UDP

I'm trying to create a simple Node.js server that receives files from clients via UDP. The problem I'm having is that every time I try to transmit a large file (anything over 100kb), the server doesn't seem to respond. So far I've been successful at transmitting files up to 50kb.

Is there any way to resolve this issue?

Client Code:

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

Server Code:

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

Upvotes: 2

Views: 3546

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17505

From the dgram docs:

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.

You can't send datagrams of more than 65,507 bytes. That's a hard limit on UDP. It sounds like you should be using a higher-level protocol for these files.

Upvotes: 7

Related Questions