Hey Guys,
So I have been using Express to write some quick Node apps and am
doing well with it. However, I have a project where I need to use the
following Web Socket Node library:
http://github.com/miksago/node-websocket-server
It is pretty close to the ever-changing spec, but works really well.
However, I'm having difficulty getting it to play nice with Express.
I saw in a recent thread about just using Socket.IO but that is not an
option for me. I would like to hi-jack the request similar to the way
it was mentioned in the prior thread, but am not sure how to do it.
With Express I have this:
configure(function() {
set("root", __dirname)
use(Logger)
use(Static, { path: require("path").join(__dirname, "..",
"public") })
enable("show exceptions")
})
get("/", function() {
this.render("index.html.haml")
})
// Must run with a null host -- heroku requirment
run(parseInt(process.env.PORT || 8000), null)
and with the websocket node server library I have this:
var sys = require('sys'),
fs = require('fs'),
ws = require('./lib/ws');
// Debug flag
var debug = true;
// Logging helper
function log(message)
{
if (debug)
{
sys.log(message);
}
}
// Default data object
var defaultData = { 'type': '', 'sender': '', 'data': null };
// Normalize an object with the default data
function normalize(obj)
{
for (var key in defaultData)
{
if (!obj[key])
{
obj[key] = defaultData[key];
}
}
}
// Create server
var server = ws.createServer({ debug: debug });
server.addListener('listening', function() {
log('WebSocket server listening for connections...');
});
// Handle WebSocket Requests
server.addListener('connection', function(conn){
log('Client connected: ' + conn._id);
var data = { 'type': 'identity', 'sender': conn._id };
normalize(data);
server.send(conn._id, JSON.stringify(data));
data.type = 'connected';
server.broadcast(JSON.stringify(data));
conn.addListener('message', function(message) {
log('Broadcasting message from from ' + conn._id + ': ' + message);
var data = JSON.parse(message);
normalize(data);
data.sender = conn._id;
server.broadcast(JSON.stringify(data));
});
});
server.addListener('close', function(conn) {
log('Client disconnected: ' + conn._id);
var data = { 'type': 'disconnected', 'sender': conn._id };
normalize(data);
server.broadcast(JSON.stringify(data));
});
// Listen on port 8000
server.listen(8000, "localhost");
Any ideas on how to hi-jack with this type of setup?
Thanks!
Joe