简体   繁体   中英

How to bind socket to more than one port, NodeJS

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?

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

或者,您可以绑定多个套接字,将它们包装成流,然后组合流以获得单个套接字的感觉。

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