Skip to content

Instantly share code, notes, and snippets.

@DomBurf
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DomBurf/2b725ede51dffaf10c29 to your computer and use it in GitHub Desktop.
Save DomBurf/2b725ede51dffaf10c29 to your computer and use it in GitHub Desktop.
A very simple TCP chat server written in Node.js
//ooen all required modules
var net = require('net');
var util = require('util');
//declare the sockets array and port number
var sockets = [];
var port = 4000;
//start the chat server
require('net').createServer(function(socket){
//give the socket a unique handle
socket.name = socket.remoreAddress + ':' + socket.remotePort;
//add the new socket to the socket array
sockets.push(socket);
//welcome message and inform other registered sockets
//that a new socket has joined the chat
socket.write('Welcome ' + socket.name + ' to the chat service\n');
broadcastMessage(socket.name + ' has joined the chat service\n', socket);
//broadcast the message to all registered clients
socket.on('data', function(data){
broadcastMessage(data, socket);
});
//inform other registered clients when a socket leaves the chat
socket.on('end', function(){
var pos = sockets.indexOf(socket);
if (pos > 0){
broadcast(socket.name + ' has left the chat service\n');
sockets.splice(pos, 1);
}
});
//Broadcast message to all registered sockets
function broadcastMessage(message, sender) {
sockets.forEach(function (client) {
if (client === sender) {
return;
}
if (message && message.length > 0){
client.write(message);
}
});
// write the message to standard output too
process.stdout.write(message);
}
}).listen(port);
console.log('Chat server listening on port ' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment