Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created August 21, 2011 22:30
Show Gist options
  • Save fearofcode/1161274 to your computer and use it in GitHub Desktop.
Save fearofcode/1161274 to your computer and use it in GitHub Desktop.
A toy chat server for node.js
net = require('net');
var sockets = [];
var s = net.Server(function(socket) {
sockets.push(socket);
var index = sockets.indexOf(socket);
socket.on('data', function(d) {
for(var i = 0; i < sockets.length; i++) {
// don't write to our own socket since we typed the
// message
if(i !== index) {
sockets[i].write("socket " + i + ": " + d);
}
}
});
// remove sockets that disconnect from the array
socket.on('end', function() {
sockets.splice(index,1);
});
});
s.listen(8000);
/* sample session:
run the following at terminal tab A:
$ node toy-chat-server.js
terminal tab B: telnet to localhost on port 8000 and type 'hi', etc
terminal tab C: telnet to localhost on port 8000 and type "what's up",
etc
stop the server by typing "killall -2 node" in a new tab
output in tabs B and C:
wkh@ubuntu:~/code$ telnet localhost 8000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
socket 0: what's up?
not much, you?
socket 0: just checking out this little chat server with node.js. it works!
i know. sweet!
socket 0: totally. catch you later.
later on bro
Connection closed by foreign host.
wkh@ubuntu:~/code$
wkh@ubuntu:~/code$ telnet localhost 8000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
socket 1: hi
what's up?
socket 1: not much, you?
just checking out this little chat server with node.js. it works!
socket 1: i know. sweet!
totally. catch you later.
socket 1: later on bro
Connection closed by foreign host.
wkh@ubuntu:~/code$
so you can see, it works.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment