Node JS: Ping Server and UDP Client

I want to create a little ping script. I am new to node js. My ultimate goal is to make the client ping the server. I want the server to confirm the packet by registering the message in the console, and I want it to send the same packet / message back to the client.

This is what I have so far:

Server:

var PORT = 33333; var HOST = '127.0.0.1'; var dgram = require('dgram'); var server = dgram.createSocket('udp4'); server.on('listening', function () { var address = server.address(); console.log('UDP Server listening on ' + address.address + ":" + address.port); }); server.on('message', function (message, remote) { console.log(remote.address + ':' + remote.port +' - ' + message); // I added a server.send but it gave me an infinite loop in the server console }); server.bind(PORT, HOST); 

Client:

 var PORT = 33333; var HOST = '127.0.0.1'; var dgram = require('dgram'); var message = new Buffer('My KungFu is Good!'); var client = dgram.createSocket('udp4'); client.on('message', function (message, remote) { console.log("The packet came back"); }); client.send(message, 0, message.length, PORT, HOST, function(err, bytes) { if (err) throw err; console.log('UDP message sent to ' + HOST +':'+ PORT); count++; }); 

UPDATE:

Thanks! It really helped. But I have another question. Say I want to send a packet in a certain number of bytes. I would replace "message.length" with 1000 for 1kb correctly? But I get the error message 'throw new Error (' Offset + length outside the buffer length ');'

I don’t quite understand why.

+6
source share
1 answer

One thing is to send data, and the other is to receive it. Since UDP is bidirectional, there is actually no strict difference between the client and server. Thus, your server and client code will be almost the same, the difference is that in fact one will send packets, and the others will only answer. Also note that you have an infinite loop, because you are probably using .send variables with the PORT and HOST variables, and you need to send them to another host / port pair.

Here is an example:

server

 var host = "127.0.0.1", port = 33333; var dgram = require( "dgram" ); var server = dgram.createSocket( "udp4" ); server.on( "message", function( msg, rinfo ) { console.log( rinfo.address + ':' + rinfo.port + ' - ' + msg ); server.send( msg, 0, msg.length, rinfo.port, rinfo.address ); // added missing bracket }); server.bind( port, host ); 

client

 // NOTE: the port is different var host = "127.0.0.1", port = 33334; var dgram = require( "dgram" ); var client = dgram.createSocket( "udp4" ); client.on( "message", function( msg, rinfo ) { console.log( "The packet came back" ); }); // client listens on a port as well in order to receive ping client.bind( port, host ); // proper message sending // NOTE: the host/port pair points at server var message = new Buffer( "My KungFu is Good!" ); client.send(message, 0, message.length, 33333, "127.0.0.1" ); 
+9
source

All Articles