简体   繁体   中英

using node.js to listen for udp datagrams

I am working on a project where a C application sends udp datagrams from port 44044 and I would like to use node.js v0.10.20 to simply echo these packets to the console.

I use the classical examples to connect:

var dgram = require('dgram');
var port = 44044;

socket = dgram.createSocket('udp4');

socket.on('message', function (msg, info){
    console.log(msg.toString());
 });

socket.on('listening', function(){
    var address = socket.address();
    console.log("listening on :" = address.address + ":" + address.port);
});

socket.bind(port);

However, when I run the example, my C application complains that the port 44044 it uses for broadcasts is already in use. Conversely, if I start my C application first, the node.js application returns immediately with an error "Error: bind EADDRINUSE".

Now I understand that this means that I have two servers that are trying to serve on the same port. But what I don't get is how can I get a node thread that will listen to udp broadcasts on port 44044? Reading node.js documentation has not helped me solve this issue.

Try using SO_REUSEADDR in your C program and in your node app use:

socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });

instead of:

socket = dgram.createSocket('udp4');

C app sends from port 44044. What port does it send to ? That's the port your node.js program needs to listen on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM