Skip to content

Commit

Permalink
Userlist is now sync'd between clients
Browse files Browse the repository at this point in the history
Added a few comments as well
  • Loading branch information
ubergeek42 committed Jun 24, 2012
1 parent 3a730cc commit b2e61a6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
8 changes: 3 additions & 5 deletions public/js/main.js
@@ -1,18 +1,16 @@
define(function(require) {
var $ = require('jquery');
var socket = io.connect('http://localhost:8000');
var socket = io.connect();

socket.on('userlistchanged', function(data) {
console.log('Updating userlist: ' + data);
console.log('Updating userlist:');
console.log(data);
var userlist = $('#userlist');
userlist.empty();
for(user in data) {
userlist.append('<li>'+user+'</li>');
}
});
socket.on('print', function(data) {
$('#msg').text(data.msg);
});

$('#loginform').on('submit', function(e){
e.preventDefault();
Expand Down
25 changes: 19 additions & 6 deletions server.js
Expand Up @@ -8,6 +8,7 @@ util.connectToDB(function(db) {
// Global list of users currently active on the server
var users = {};


// Load models
var models = require('./models')(db);

Expand All @@ -23,18 +24,27 @@ util.connectToDB(function(db) {

var io = socketio.listen(app);
io.sockets.on('connection', function(socket) {
console.log('Connection made.');
socket.emit('print', {msg: 'Please login above'});

console.log('Connection from ' + socket.handshake.address.address);
emituserlist();

// The client is logging in
socket.on('login', function(data) {
console.log('Login from: ' + data.username);
users[data.username] = {ipaddress: socket.handshake.address.address,
s: socket};
socket.emit('print', {msg: 'Welcome ' + data.username});
console.log(users);
emituserlist();

// Send an updated userlist to everyone
var userlist = {};
for (user in users) {
userlist[user] = {username: user};
}
for (user in users) {
users[user].s.emit('userlistchanged', userlist);
}
});


// The client disconnected(Remove them from the list of active users)
socket.on('disconnect', function(data) {
console.log('client disconnected');
for(username in users) {
Expand All @@ -45,8 +55,11 @@ util.connectToDB(function(db) {
}
console.log(users);
});

// The client wants the list of users
socket.on('getusers', emituserlist);

// Sends the list of online users to the client
function emituserlist() {
var userlist = {};
for (user in users) {
Expand Down

0 comments on commit b2e61a6

Please sign in to comment.