简体   繁体   中英

UDP socket in node.js

I am trying to connect to an UDP socket on another computer using the UDP socket of node.js and I am getting the following error:

bind EADDRNOTAVAIL192.168.1.50;12345

I am using the following code:

var port = 12345;
   var host = "192.168.1.50";
   var sock = dgram.createSocket("udp4");
   sock.on("listening", function () {
       console.log("server listening ");
    });

    sock.on("error", function (err) {
        console.log("server error:\n" + err.stack);
        sock.close();
    });

    //start the UDP server with the radar port 12345
    sock.bind(port, host);

any help?

thanks

You can't bind to the remote server address! It doesn't matter what your server ip is, you should bind to one of your local interfaces. If you want to bind on all local interfaces, just bind like following:

 sock.bind(port);

You can send UDP datagrams in the following way (Sample code)

var dgram = require('dgram');

var PORT = 12345;
var HOST = '192.168.1.50';
var message = new Buffer('Pinging');

var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
   if (err) throw err;
   console.log('UDP message sent to ' + HOST +':'+ PORT);
   client.close();
});

Reference: http://www.hacksparrow.com/node-js-udp-server-and-client-example.html

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