Skip to content

Instantly share code, notes, and snippets.

@jazlalli
Created January 23, 2013 11:36
Show Gist options
  • Save jazlalli/4604622 to your computer and use it in GitHub Desktop.
Save jazlalli/4604622 to your computer and use it in GitHub Desktop.
node.js chat server
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs');
app.listen(8888);
function handler (req, res) {
fs.readFile(__dirname + req.url, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading page');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function(socket){
socket.on('set name', function(name) {
socket.set('name', name, function() {
socket.broadcast.send(name + ' has joined the conversation')
});
});
socket.on('message', function(data) {
socket.get('name', function(err, name) {
socket.broadcast.send(name + ' says: ' + data);
});
});
socket.on('disconnect', function() {
socket.get('name', function(err, name) {
socket.broadcast.send(name + ' has left the conversation.');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment