428 CHAPTER 10 WebSocket communications
The adduser event is triggered after the client makes a connection. It adds the
username to the usernames collection and then uses the socket object to call the
updatechat event on the current client to indicate to the user that the connection is
successful. The socket.broadcast object sends a message indicating that the current
client is connected. This message is broadcast to all clients except the current client.
Finally, the io.sockets.emit event broadcasts an updated user list to all clients.
The disconnect event deletes the user from the usernames list and broadcasts the
usernames to all clients. The socket.broadcast object broadcasts a disconnect message
to all clients except the current client.
- Add code to listen on port 8080 and log a message to the console stating this.
The app.js file should look like the following.
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
var usernames = {};
io.sockets.on('connection', function (socket) {
socket.on('sendchat', function (data) {
io.sockets.emit('updatechat', socket.username, data);
});
socket.on('adduser', function(username){
socket.username = username;
usernames[username] = username;
socket.emit('updatechat', 'SERVER', 'you have connected');
socket.broadcast.emit('updatechat', 'SERVER'
, username + ' has connected');
io.sockets.emit('updateusers', usernames);
});
socket.on('disconnect', function(){
delete usernames[socket.username];
io.sockets.emit('updateusers', usernames);
socket.broadcast.emit('updatechat', 'SERVER'
, socket.username + ' has disconnected');
});
});
var port = 8080;
server.listen(port);
console.log('Listening on port: ' + port);