Skip to content

Instantly share code, notes, and snippets.

@sumory
Forked from creationix/chatServer.js
Created July 12, 2012 04:29
Show Gist options
  • Select an option

  • Save sumory/3095720 to your computer and use it in GitHub Desktop.

Select an option

Save sumory/3095720 to your computer and use it in GitHub Desktop.

Revisions

  1. @creationix creationix revised this gist Nov 19, 2010. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion chatServer.js
    Original file line number Diff line number Diff line change
    @@ -25,7 +25,7 @@ net.createServer(function (socket) {
    // Remove the client from the list when it leaves
    socket.on('end', function () {
    clients.splice(clients.indexOf(socket), 1);
    broadcast(socket.name + "left the chat.\n");
    broadcast(socket.name + " left the chat.\n");
    });

    // Send a message to all clients
  2. @invalid-email-address Anonymous created this gist Nov 19, 2010.
    45 changes: 45 additions & 0 deletions chatServer.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    // Load the TCP Library
    net = require('net');

    // Keep track of the chat 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);

    // Send a nice welcome message and announce
    socket.write("Welcome " + socket.name + "\n");
    broadcast(socket.name + " joined the chat\n", socket);

    // Handle incoming messages from clients.
    socket.on('data', function (data) {
    broadcast(socket.name + "> " + data, socket);
    });

    // Remove the client from the list when it leaves
    socket.on('end', function () {
    clients.splice(clients.indexOf(socket), 1);
    broadcast(socket.name + "left the chat.\n");
    });

    // Send a message to all clients
    function broadcast(message, sender) {
    clients.forEach(function (client) {
    // Don't want to send it to sender
    if (client === sender) return;
    client.write(message);
    });
    // Log it to the server output too
    process.stdout.write(message)
    }

    }).listen(5000);

    // Put a friendly message on the terminal of the server.
    console.log("Chat server running at port 5000\n");