Skip to content

Instantly share code, notes, and snippets.

@iamtrk
Last active December 19, 2015 19:28
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 iamtrk/6006101 to your computer and use it in GitHub Desktop.
Save iamtrk/6006101 to your computer and use it in GitHub Desktop.
A Simple chat server implemented in Node.js
//fs module is required for writing conversations and host info logging.
var net = require('net');
var fs = require('fs');
var sockets = [];
var people = {};
// Hosts are saved in hosts file and conversation is saved in conversation file.
var hosts = 'hosts.txt';
var conv = 'conversation.txt';
var server = net.createServer(function(socket){
sockets.push(socket);
var host = socket.remoteAddress+":"+socket.remotePort;
socket.write("Hellow "+host+'\n');
fs.appendFile('hosts.txt',host+'\n', function(err){
if(err) throw err;
console.log(host+" host is added to the list successfully");
});
socket.on('data',function(data){
// appendFile is an Asynchronous call.
fs.appendFile('conversation.txt',host+":"+data,"utf-8", function(err){
if(err) throw err; });
for(var i=0;i<sockets.length;i++){
if(sockets[i]==this) continue;
sockets[i].write(host+"->"+data); }
});
socket.on('end',function(){
var i = sockets.indexOf(socket);
sockets.splice(i,1);
});
});
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment