Created
May 4, 2012 15:42
-
-
Save benhosmer/2595615 to your computer and use it in GitHub Desktop.
A Simple node.js chat server using telent from O'reilly's node up and running.
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
// A Simple nod.js chat server using telent from O'reilly's node up and running | |
var net = require('net') | |
var chatServer = net.createServer() | |
clientList = [] | |
chatServer.on('connection', function(client) { | |
client.name = client.remoteAddress + ':' + client.remotePort | |
client.write('Hi ' + client.name + '!\n'); | |
clientList.push(client) | |
client.on('data', function(data) { | |
broadcast(data, client) | |
}) | |
client.on('end', function() { | |
clientList.splice(clientList.indexOf(client), 1) | |
}) | |
}) | |
function broadcast(message, client) { | |
// Echo the sending client's name to all clients receiving the message | |
for(var i=0;i<clientList.length;i+=1) { | |
if(client !== clientList[i]) { | |
clientList[i].write(client.name + " said: " + message) | |
} | |
// Echo the >> character so client sending knows he sent it | |
else client.write(">> " + message) | |
} | |
} | |
chatServer.listen(9000) | |
console.log('Listening on port 9000...'); |
Let's figure out how to include the date and time each message was sent, and echo that back to the client(s). It is probably pretty simple to do with javascript.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems a little cleaner for some reason. I wrapped the client.write for the sending client within the broadcast on line 32