Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // var net = require("net"), sys = require('util');
- //
- // clients
- //
- // var server = net.createServer(function (stream) {
- // stream.setEncoding("utf8");
- // stream.on("connect", function (socket) {
- // stream.write("hello\0");
- // sys.puts(sys.inspect(stream, false));
- // });
- // stream.on("data", function (data) {
- // stream.write(data + "\0");
- // });
- // stream.on("end", function () {
- // stream.end();
- // });
- // });
- // server.listen(31337, "127.0.0.1");
- /**
- * @author onteria
- * @namespace Server
- */
- var net = require('net');
- var clients = [];
- var server = net.createServer();
- /**
- * @function
- * @description Call the function callback on each client
- * @param {function} callback The callback to apply to each client
- * @example
- * actOnClients(function(client) {
- * client.write("Hello");
- * });
- */
- function actOnClients(callback) {
- for (var i = 0; i < clients.length; i++) {
- callback(clients[i]);
- }
- }
- /**
- * @function
- * @description Broadcast a message to all clients
- * @param {string} message The message to broadcast
- * @param {array} filter_clients A list of clients to filter
- * @requires actOnClients
- */
- function broadcastMessage(message,filter_clients) {
- var filter = (filter_clients) ? filter_clients : [];
- actOnClients(function(current_client) {
- if( filter.indexOf(current_client) == -1 ) {
- current_client.write(message);
- }
- });
- }
- server.on('connection', function(client) {
- broadcastMessage('[info] Client connection from ' + client.remoteAddress + "\r\n");
- clients.push(client);
- // Here we broadcast to all clients except the one that sent
- // the message
- client.on('data', function(data) {
- broadcastMessage(data, [client]);
- });
- client.on('close', function() {
- for(var i = 0; i < clients.length; i++) {
- if(clients[i] == client) {
- clients.splice(i,1);
- break;
- }
- }
- broadcastMessage('[info] Client disconnect from ' + client.remoteAddress + "\r\n");
- });
- });
- server.listen(31337, '127.0.0.1');
Add Comment
Please, Sign In to add comment