Skip to content

Instantly share code, notes, and snippets.

@L1fescape
Created May 1, 2013 16:02
Show Gist options
  • Save L1fescape/5496200 to your computer and use it in GitHub Desktop.
Save L1fescape/5496200 to your computer and use it in GitHub Desktop.
Simple Chat Server Nodejs chat server that serves two static files (index.html and jquery.js), allowing clients to communicate via a basic web interface. Use npm install socket.io node chat-server.js
// Global variables
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, url = require('url')
, port = 1337
// initialize http server
app.listen(port);
console.log("Listening on port", port)
// define http handler
function handler (req, res) {
// grab requeseted url path
var pathname = url.parse(req.url).pathname;
// index
if (pathname == "/") {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
}
);
}
// jquery
else if (pathname == "/jquery.js") {
fs.readFile(__dirname + '/jquery.js',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading jquery.js');
}
res.writeHead(200);
res.end(data);
}
);
}
}
// listen for socket.io requests
io.sockets.on('connection', function (socket) {
socket.emit('recieve', { hello: 'world' });
socket.on('send', function (data) {
// disable xss
for (var i in data)
data[i] = data[i].replace(/[<>/]/g, "");
// send message to clients
io.sockets.emit('receive', data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment