Challenge 5 Solution
Video Course on Building Web Applications with Node.jsSometimes your app needs to be on a visible public address
Socket
explains ngrok.com service: forward your localhost post to a public url (it's a reverse proxy)
Socket set
method
to set a persistent value (like a cookie)
socket.on('nick', function(nick) {socket.set('nickname', nick);});
then to use it:
socket.get('nickname', function(err, nick) { // use the nickname in the callback})
// Handle socket traffic
io.sockets.on('connection', function (socket) {
// Set the nickname property for a given client
socket.on('nick', function(nick) {
socket.set('nickname', nick);
});
// Relay chat data to all clients
socket.on('chat', function(data) {
socket.get('nickname', function(err, nick) {
var nickname = err ? 'Anonymous' : nick;
var payload = {
message: data.message,
nick: nickname
};
socket.emit('chat',payload);
socket.broadcast.emit('chat', payload);
});
});
});
So to clarify:io.sockets.on("connection", cb)
the
connection
event happens each time a new client is connected and everything inside the callback related to that one clientsocket.emit(//...)
and socket.broadcast.emit(//...)
you can also just use
io.sockets.emit('chat', payload)
to broadcast to all connected clients. instead of the two lines:socket.emit('chat',payload);
socket.broadcast.emit('chat', payload);