Skip to content

Instantly share code, notes, and snippets.

@iamtrk

iamtrk/chat.js

Last active Dec 19, 2015
Embed
What would you like to do?
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