Last active
September 25, 2016 14:19
-
-
Save ethaizone/1a84a7a2f9f1fcb6c72de28a89092c59 to your computer and use it in GitHub Desktop.
Example tcp server write by NodeJS. Just telnet to port in config.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var net = require('net'); | |
// Config | |
var config = { | |
server: { | |
port: 7890 | |
} | |
}; | |
var clients = []; | |
// Add new method to net.Socket | |
net.Socket.prototype.log = function(msg) | |
{ | |
console.log(this.getName() + " -> Status: " + msg); | |
}; | |
net.Socket.prototype.getName = function(msg) | |
{ | |
return this.remoteAddress + ":" + this.remotePort; | |
}; | |
net.Socket.prototype.printLine = function(msg) | |
{ | |
this.write(String(msg) + "\n"); | |
}; | |
net.Socket.prototype.broadcast = function(msg) | |
{ | |
for (var i = 0; i < clients.length; i++) { | |
var childSocket = clients[i]; | |
if (childSocket.getName() != this.getName()) { | |
childSocket.printLine(msg); | |
} | |
} | |
}; | |
net.createServer(function (socket) { | |
clients.push(socket); | |
socket.log('Connected!'); | |
socket.on('data', function (raw) { | |
raw = raw.toString().trim(); | |
socket.log('Received data ' + raw.length + ' bytes'); | |
if (raw == 'getClients') { | |
socket.printLine("Client list."); | |
for (var i = 0; i < clients.length; i++) { | |
var childSocket = clients[i]; | |
socket.printLine('-> ' + childSocket.getName()); | |
} | |
socket.log('Send client list.'); | |
return; | |
} | |
if (raw == 'broadcast') { | |
socket.broadcast('Test broadcast!!'); | |
socket.printLine("Broadcasted."); | |
socket.log('Broadcasted.'); | |
return; | |
} | |
try { | |
// do anythink to raw data blabla.... | |
} catch (e) { | |
console.log(e); | |
socket.printLine('Process raw data failed. View console log for more info'); | |
} | |
}); | |
socket.on('end', function () { | |
// Unset client from clients | |
for (var i = 0; i < clients.length; i++) { | |
var childSocket = clients[i]; | |
if (childSocket.getName() == socket.getName()) { | |
clients.splice(i, 1); | |
} | |
} | |
socket.log('Disconnect!'); | |
}); | |
}).listen(config.server.port); | |
console.log('Listen on ' + config.server.port + '.'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment