Skip to content

Instantly share code, notes, and snippets.

@omaraflak
Last active April 26, 2016 15:42
Show Gist options
  • Save omaraflak/41706a476f0a4d5c058353a54f18fd3c to your computer and use it in GitHub Desktop.
Save omaraflak/41706a476f0a4d5c058353a54f18fd3c to your computer and use it in GitHub Desktop.
net server in nodejs to forward messages.
var net = require('net');
var sockets = [];
var svr = net.createServer(function(sock) {
console.log('Connected: ' + sock.remoteAddress + ':' + sock.remotePort);
sockets.push(sock);
sock.write('Welcome to the server!');
sock.on('data', function(data) {
for (var i=0; i<sockets.length ; i++) {
if (sockets[i] != sock) {
if (sockets[i]) {
sockets[i].write(data);
}
}
}
});
sock.on('end', function() {
console.log('Disconnected: ' + sock.remoteAddress + ':' + sock.remotePort);
var idx = sockets.indexOf(sock);
if (idx != -1) {
delete sockets[idx];
}
});
});
var svraddr = '192.168.0.8';
var svrport = 1234;
svr.listen(svrport, svraddr);
console.log('Server Created at ' + svraddr + ':' + svrport + '\n');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment