Skip to content

Instantly share code, notes, and snippets.

@ethaizone
Last active September 25, 2016 14:19
Show Gist options
  • Save ethaizone/1a84a7a2f9f1fcb6c72de28a89092c59 to your computer and use it in GitHub Desktop.
Save ethaizone/1a84a7a2f9f1fcb6c72de28a89092c59 to your computer and use it in GitHub Desktop.
Example tcp server write by NodeJS. Just telnet to port in config.
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