Created
March 19, 2014 21:51
-
-
Save dtrenz/9652176 to your computer and use it in GitHub Desktop.
Example node + socket.io chat app using express.
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
#!/usr/bin/env node | |
var express = require('express'); | |
var app = express(); | |
var server_port = process.env.PORT || 5000; | |
var server = require('http').createServer(app); | |
var io = require('socket.io').listen(server); | |
var users = {}; | |
server.listen(server_port); | |
console.log('###Express server listening on port %d', server_port); | |
app.use(express.static(__dirname + '/')); | |
io.sockets.on('connection', function(socket) { | |
socket.on('set nickname', function(nickname) { | |
user = getUserByNick(nickname); | |
if (user) { | |
socket.emit('ready', { id: user.id } ); | |
} else { | |
user = registerUser(nickname, socket.id); | |
} | |
socket.set('nickname', user.nickname, function() { | |
socket.set('userID', user.id, function() { | |
socket.emit('ready', { id: user.id } ); | |
}); | |
}); | |
}); | |
socket.on('update visible users', function(users) { | |
for (var i in users) { | |
socket.join(users[i]); | |
} | |
}); | |
socket.on('msg', function(msg) { | |
socket.get('nickname', function(err, nickname) { | |
var user = users[nickname]; | |
if (user) { | |
socket.broadcast.to(user.id).emit('chat update', { nickname: user.nickname, text: msg }); | |
} | |
}); | |
}); | |
}); | |
function getUserByNick(nickname) { | |
return users[nickname]; | |
} | |
function registerUser(nickname, socketID) { | |
if (users[nickname] == undefined) { | |
var userId = Object.keys(users).length + 100; | |
users[nickname] = { | |
id: userId, | |
nickname: nickname, | |
socketId: socketID | |
}; | |
} | |
return users[nickname]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment