I want to create a small ping script. I am a beginner in node js. My ultimate small goal is to have the client ping the server. I want the server to acknowledge the packet by logging the message in the console and I want it to send back 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! That really helped. But I have another question. Let's say I want to send the packet in a specific number of bytes. I would replace 'message.length' with 1000 for 1kb right? But I get an error 'throw new Error('Offset + length beyond buffer length');'
I don't quite understand why.
One thing is sending data and the other thing is receiveing it. Since UDP protocol is bidirectional, then actually there is no strict difference between client and server. So your server and client code will be almost the same, the difference is that actually one will send packets and other will only respond. Also note that you have an infinite loop, because your probably using .send
with PORT
and HOST
variables and you have to send to different host/port pair.
Here's 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" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With