Last active
December 19, 2015 19:28
-
-
Save iamtrk/6006101 to your computer and use it in GitHub Desktop.
A Simple chat server implemented in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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