Skip to content

Instantly share code, notes, and snippets.

@phuesler
Created November 16, 2013 15:41
Show Gist options
  • Save phuesler/7501605 to your computer and use it in GitHub Desktop.
Save phuesler/7501605 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
// Start with nohup node log_server.js > output.log &
// Load the TCP Library
net = require('net');
// Keep track of the clients
var clients = [];
// Start a TCP Server
net.createServer(function (socket) {
// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort;
// Put this new client in the list
clients.push(socket);
broadcast(socket.name + " connected\n");
// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(data);
});
// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " disconnected.\n");
});
function broadcast(message) {
process.stdout.write(message)
}
}).listen(5555);
// Put a friendly message on the terminal of the server.
console.log("TCP server running on 5555\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment