如何将套接字绑定到多个端口NodeJS

时间:2014-06-30 17:52:24

标签: javascript node.js sockets udp

我已经设置了一个节点应用程序,它从一个IP地址的端口接收数据包,并将内容提供给一个网页。此IP地址的流量通过两个端口9999和10000.我的应用程序具有以下代码:

    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

当我在终端中运行节点应用程序时,收到错误

dgram.js:163
throw new Error('Socket is already bound');

其中dgram.js是Nodejs库的一部分。绑定到PORT_TWO时出错。有没有办法将套接字绑定到多个端口?

2 个答案:

答案 0 :(得分:2)

我想在这里加上我的2美分,我通常做的是创建端口和Ips数组并逐个输入循环绑定

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

答案 1 :(得分:0)

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