Skip to content

Instantly share code, notes, and snippets.

@benhosmer
Created May 4, 2012 15:42
Show Gist options
  • Save benhosmer/2595615 to your computer and use it in GitHub Desktop.
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.
// 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...');
@benhosmer
Copy link
Author

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