From c3580921cb471a328b9996fceec90e24d4107a8b Mon Sep 17 00:00:00 2001 From: thefosk Date: Thu, 19 Mar 2015 02:23:24 -0700 Subject: [PATCH] adding udp support --- lib/server.js | 37 ++++++++++++++++++++++++++++--------- site/index.html | 34 +++++++++++++++++++++++++++------- 2 files changed, 55 insertions(+), 16 deletions(-) diff --git a/lib/server.js b/lib/server.js index e628f82..0c009f7 100644 --- a/lib/server.js +++ b/lib/server.js @@ -1,10 +1,9 @@ var cluster = require('cluster'); var net = require('net'); +var dgram = require('dgram'); var numCPUs = require('os').cpus().length; -function new_connection(socket) { - console.log('Connection accepted for ' + socket.remoteAddress + ":" + socket.remotePort); -} +var HOST = "127.0.0.1" if (cluster.isMaster) { for (var i = 0; i < numCPUs; i++) { @@ -15,18 +14,16 @@ if (cluster.isMaster) { }); } else { - // Echo + // TCP Echo net.createServer(function(socket) { - new_connection(socket); socket.on('data', function(data) { socket.write(data); }); socket.on('error', function() {}); - }).listen(4444); + }).listen(30000); - // Info + // TCP Info net.createServer(function(socket) { - new_connection(socket); socket.on('data', function(data) { var response = { "client-ip": socket.remoteAddress, @@ -37,5 +34,27 @@ if (cluster.isMaster) { socket.write(JSON.stringify(response)); }); socket.on('error', function() {}); - }).listen(5555); + }).listen(30001); + + // UDP Echo + var udp_echo_server = dgram.createSocket("udp4"); + udp_echo_server.on("message", function(msg, rinfo) { + udp_echo_server.send(msg, 0, msg.length, rinfo.port, rinfo.address); + }); + udp_echo_server.bind(40000, HOST); + + // UDP Info + var udp_info_server = dgram.createSocket("udp4"); + udp_info_server.on("message", function(msg, rinfo) { + var response = JSON.stringify({ + "client-ip": rinfo.address, + "data": msg, + "text-data": msg.toString(), + "size": msg.length + }); + + var buffer = new Buffer(response); + udp_info_server.send(buffer, 0, buffer.length, rinfo.port, rinfo.address); + }); + udp_info_server.bind(40001, HOST); } \ No newline at end of file diff --git a/site/index.html b/site/index.html index 62d6147..1c3e716 100644 --- a/site/index.html +++ b/site/index.html @@ -3,7 +3,7 @@ - tcpbin(1): TCP Client Testing Service + tcpbin(1): TCP/UDP Client Testing Service