Guest User

Untitled

a guest
May 24th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. // Load the TCP Library
  2. net = require('net');
  3.  
  4. // Keep track of the chat clients
  5. var clients = [];
  6.  
  7. // Start a TCP Server
  8. net.createServer(function (socket) {
  9.  
  10. // Identify this client
  11. socket.name = socket.remoteAddress + ":" + socket.remotePort
  12.  
  13. // Put this new client in the list
  14. clients.push(socket);
  15.  
  16. // Send a nice welcome message and announce
  17. socket.write("Welcome " + socket.name + "\n");
  18. broadcast(socket.name + " joined the chat\n", socket);
  19.  
  20. // Handle incoming messages from clients.
  21. socket.on('data', function (data) {
  22. broadcast(socket.name + "> " + data, socket);
  23. });
  24.  
  25. // Remove the client from the list when it leaves
  26. socket.on('end', function () {
  27. clients.splice(clients.indexOf(socket), 1);
  28. broadcast(socket.name + " left the chat.\n");
  29. });
  30.  
  31. // Send a message to all clients
  32. function broadcast(message, sender) {
  33. clients.forEach(function (client) {
  34. // Don't want to send it to sender
  35. if (client === sender) return;
  36. client.write(message);
  37. });
  38. // Log it to the server output too
  39. process.stdout.write(message)
  40. }
  41.  
  42. }).listen(5000);
  43.  
  44. // Put a friendly message on the terminal of the server.
  45. console.log("Chat server running at port 5000\n");
Add Comment
Please, Sign In to add comment