Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. var io = require('socket.io').listen(server);
  2. io.sockets.on('connection', function (socket) {
  3.  
  4. // when the client emits 'sendchat', this listens and executes
  5. socket.on('sendchat', function (data) {
  6. // we tell the client to execute 'updatechat' with 2 parameters
  7. io.sockets.emit('updatechat', socket.username, data);
  8. });
  9.  
  10. // when the client emits 'adduser', this listens and executes
  11. socket.on('adduser', function(username){
  12. // we store the username in the socket session for this client
  13. socket.username = username;
  14. // add the client's username to the global list
  15. usernames[username] = username;
  16. // echo to client they've connected
  17. socket.emit('updatechat', 'SERVER', 'you have connected');
  18. // echo globally (all clients) that a person has connected
  19. socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
  20. // update the list of users in chat, client-side
  21. io.sockets.emit('updateusers', usernames);
  22. });
  23.  
  24. // when the user disconnects.. perform this
  25. socket.on('disconnect', function(){
  26. // remove the username from global usernames list
  27. delete usernames[socket.username];
  28. // update list of users in chat, client-side
  29. io.sockets.emit('updateusers', usernames);
  30. // echo globally that this client has left
  31. socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
  32. });
  33. });
  34.  
  35. app.get('/', routes.index);
  36.  
  37. exports.index = function(req, res){
  38. res.render('index', { title: 'Express' });
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement