Created
May 1, 2013 16:02
-
-
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
This file contains hidden or 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
// 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