index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Setup basic express server
  2. var express = require('express');
  3. var app = express();
  4. var server = require('http').createServer(app);
  5. var io = require('socket.io')(server);
  6. var port = process.env.PORT || 8080;
  7. server.listen(port, function () {
  8. console.log('Server listening at port %d', port);
  9. });
  10. // Routing
  11. app.use(express.static(__dirname + '/public'));
  12. // Chatroom
  13. var numUsers = 0;
  14. io.on('connection', function (socket) {
  15. var addedUser = false;
  16. // when the client emits 'new message', this listens and executes
  17. socket.on('new message', function (data) {
  18. // we tell the client to execute 'new message'
  19. socket.broadcast.emit('new message', {
  20. username: socket.username,
  21. message: data
  22. });
  23. });
  24. // when the client emits 'add user', this listens and executes
  25. socket.on('add user', function (username) {
  26. if (addedUser) return;
  27. // we store the username in the socket session for this client
  28. socket.username = username;
  29. ++numUsers;
  30. addedUser = true;
  31. socket.emit('login', {
  32. numUsers: numUsers
  33. });
  34. // echo globally (all clients) that a person has connected
  35. socket.broadcast.emit('user joined', {
  36. username: socket.username,
  37. numUsers: numUsers
  38. });
  39. });
  40. // when the client emits 'typing', we broadcast it to others
  41. socket.on('typing', function () {
  42. socket.broadcast.emit('typing', {
  43. username: socket.username
  44. });
  45. });
  46. // when the client emits 'stop typing', we broadcast it to others
  47. socket.on('stop typing', function () {
  48. socket.broadcast.emit('stop typing', {
  49. username: socket.username
  50. });
  51. });
  52. // when the user disconnects.. perform this
  53. socket.on('disconnect', function () {
  54. if (addedUser) {
  55. --numUsers;
  56. // echo globally that this client has left
  57. socket.broadcast.emit('user left', {
  58. username: socket.username,
  59. numUsers: numUsers
  60. });
  61. }
  62. });
  63. });