Last active
April 26, 2016 15:42
-
-
Save omaraflak/41706a476f0a4d5c058353a54f18fd3c to your computer and use it in GitHub Desktop.
net server in nodejs to forward messages.
This file contains 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'); | |
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