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 );
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" );
source share