title: Node JS: Ping Server & Client UDP
body: <p>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.</p>
  
  <p>This is what I have so far:</p>
  
  <p><strong>Server:</strong></p>
  
  <pre><code>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);
  </code></pre>
  
  <p><strong>Client:</strong></p>
  
  <pre><code>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++;
  });
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>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');'</p>
  
  <p>I don't quite understand why.</p>