Reputation: 43
I have set up a node application which receives packets from a Port at an IP address and serves the contents to a web-page. This IP address has traffic going through two ports, 9999 and 10000. My application has the following code:
var PORT_ONE = 9999;
var PORT_TWO = 10000;
var SENSOR = '239.0.0.1';
var client = require('dgram').createSocket('udp4');
var dns = require('dns');
/* Client starts listening on IP */
client.on('listening', function () {
console.log('UDP Client listening on ' + SENSOR + ":" + PORT_TWO);
client.setMulticastTTL(1);
client.addMembership(SENSOR);
});
/* Client receives a message */
client.on('message', function (message, remote) {
var tempMessage = message.toString(); //cast Buffer var to String
var delimiter = "\n";
var tempData = tempMessage.split(delimiter);
console.log('From: ' + remote.address + ':' + remote.port +' - \n' + message);
var data = {
ip: [SENSOR],
info: [tempData]
};
sendMessage(data);
});
client.bind(PORT_ONE);
client.bind(PORT_TWO); //error here
When I run my node application in the terminal, I receive the error
dgram.js:163
throw new Error('Socket is already bound');
Where dgram.js is part of the Nodejs libraries. The error comes when binding to PORT_TWO. Is there a way to bind the socket to more than one port?
Upvotes: 3
Views: 2907
Reputation: 65
I want to add my 2 cents here, what I normally do is create array of ports and Ips and put in for loop binding on them one by one
udpclients = [5550,5551];
udpsockets=[]
var dgram = require('dgram');
udpclients.forEach(function(port){
var udpServer = dgram.createSocket('udp4');
udpServer.bind(port,'127.0.0.1')
udpServer.on('listening', function() {
var address = udpServer.address()
console.log("listening"+address.address+" port::"+address.port)
});
udpServer.on('message', function(msg, rinfo) {
console.log("message received :: "+ msg +" address::"+rinfo.address+ "port = "+ rinfo.port )
});
});
Upvotes: 2
Reputation: 1178
Or you can bind multiple sockets, wrap them into streams and then combine streams to get feeling of one single socket.
Upvotes: 0