Skip to content

Commit

Permalink
Updated package.json, added numUsers int on server, and used io short…
Browse files Browse the repository at this point in the history
…hand notation
  • Loading branch information
grant committed Feb 15, 2014
1 parent 1860aa4 commit cfb2a26
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
8 changes: 5 additions & 3 deletions examples/chat/app.js
Expand Up @@ -23,13 +23,14 @@ app.get('/style.css', function (req, res) {

// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

io.sockets.on('connection', function (socket) {
io.on('connection', function (socket) {

// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'update chat' with 2 parameters
io.sockets.emit('update chat', socket.username, data);
io.emit('update chat', socket.username, data);
});

// when the client emits 'add user', this listens and executes
Expand All @@ -38,6 +39,7 @@ io.sockets.on('connection', function (socket) {
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
++numUsers;
// echo to client they've connected
socket.emit('update chat', 'SERVER', 'you (' + username + ') have connected. ' + getNumberOfUsersString());
// echo globally (all clients) that a person has connected
Expand All @@ -48,14 +50,14 @@ io.sockets.on('connection', function (socket) {
socket.on('disconnect', function () {
// remove the username from global usernames list
delete usernames[socket.username];
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('update chat', 'SERVER', socket.username + ' has disconnected. ' + getNumberOfUsersString());
});
});

// Gets a string that contains the number of users in the chatroom
function getNumberOfUsersString () {
var numUsers = Object.keys(usernames).length;
var numUsersString = '<span class="log">(' + numUsers + ' ' + ((numUsers === 1) ? 'user' : 'users') + ' in chatroom)</span>';
return numUsersString;
}
4 changes: 1 addition & 3 deletions examples/chat/package.json
Expand Up @@ -3,10 +3,8 @@
"version": "0.0.0",
"description": "A simple chat client using socket.io",
"main": "app.js",
"scripts": {
"test": "node app"
},
"author": "Grant Timmerman",
"private": true,
"license": "BSD",
"dependencies": {
"express": "3.4.8"
Expand Down

0 comments on commit cfb2a26

Please sign in to comment.