Guest User

Untitled

a guest
Oct 11th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. // var net = require("net"), sys = require('util');
  2. //
  3. // clients
  4. //
  5. // var server = net.createServer(function (stream) {
  6. // stream.setEncoding("utf8");
  7. // stream.on("connect", function (socket) {
  8. // stream.write("hello\0");
  9. // sys.puts(sys.inspect(stream, false));
  10. // });
  11. // stream.on("data", function (data) {
  12. // stream.write(data + "\0");
  13. // });
  14. // stream.on("end", function () {
  15. // stream.end();
  16. // });
  17. // });
  18. // server.listen(31337, "127.0.0.1");
  19.  
  20. /**
  21. * @author onteria
  22. * @namespace Server
  23. */
  24. var net = require('net');
  25. var clients = [];
  26. var server = net.createServer();
  27.  
  28. /**
  29. * @function
  30. * @description Call the function callback on each client
  31. * @param {function} callback The callback to apply to each client
  32. * @example
  33. * actOnClients(function(client) {
  34. * client.write("Hello");
  35. * });
  36. */
  37. function actOnClients(callback) {
  38. for (var i = 0; i < clients.length; i++) {
  39. callback(clients[i]);
  40. }
  41. }
  42.  
  43. /**
  44. * @function
  45. * @description Broadcast a message to all clients
  46. * @param {string} message The message to broadcast
  47. * @param {array} filter_clients A list of clients to filter
  48. * @requires actOnClients
  49. */
  50. function broadcastMessage(message,filter_clients) {
  51. var filter = (filter_clients) ? filter_clients : [];
  52.  
  53. actOnClients(function(current_client) {
  54. if( filter.indexOf(current_client) == -1 ) {
  55. current_client.write(message);
  56. }
  57. });
  58. }
  59.  
  60. server.on('connection', function(client) {
  61.  
  62. broadcastMessage('[info] Client connection from ' + client.remoteAddress + "\r\n");
  63. clients.push(client);
  64.  
  65. // Here we broadcast to all clients except the one that sent
  66. // the message
  67. client.on('data', function(data) {
  68. broadcastMessage(data, [client]);
  69. });
  70.  
  71. client.on('close', function() {
  72. for(var i = 0; i < clients.length; i++) {
  73. if(clients[i] == client) {
  74. clients.splice(i,1);
  75. break;
  76. }
  77. }
  78.  
  79. broadcastMessage('[info] Client disconnect from ' + client.remoteAddress + "\r\n");
  80. });
  81.  
  82. });
  83.  
  84. server.listen(31337, '127.0.0.1');
Add Comment
Please, Sign In to add comment