Skip to content

Instantly share code, notes, and snippets.

@fzzzy
Created April 3, 2012 02:36
Show Gist options
  • Save fzzzy/2288903 to your computer and use it in GitHub Desktop.
Save fzzzy/2288903 to your computer and use it in GitHub Desktop.
marionette node websocket proxy
// marionette.js
"use strict";
var net = require('net');
function make_connection(cb) {
var sock = new net.Socket(),
in_buffer = "";
sock.on('connect', function(s) {
console.log("connect");
});
sock.on('data', function(d) {
var i = 0;
in_buffer += d.toString();
while ((i = in_buffer.indexOf(":")) !== -1) {
var size = parseInt(in_buffer.slice(0, i));
cb(in_buffer.substr(i + 1, size));
in_buffer = in_buffer.slice(i + size);
}
});
sock.on("drain", function() {
});
sock.connect(2828);
return {
send: function send_message(msg) {
var str = JSON.stringify(msg),
len = str.length;
// I think this is correct, but it's not tested.
sock.write(len.toString() + ':' + str);
}
}
}
/**
* Module dependencies.
*/
var http = require('http')
, wsio = require('./Code/websocket.io')
/**
* Create HTTP server.
*/
var server = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf8' });
res.end([
'<html><head><title>Hello</title><script>'
, "var ws = new WebSocket('ws://127.0.0.1:3000');"
, "ws.onerror = function(er) { console.log('er', er) };"
, "ws.onclose = function() { console.log('close') };"
, 'ws.onmessage = function (msg) { var el = document.createElement("pre"); el.appendChild(document.createTextNode(msg.data)); document.body.appendChild(el) };'
, '</script></head><body>Hello</body></html>'
].join(''));
});
/**
* Attach websocket.io
*/
var ws = wsio.attach(server)
, i = 0
ws.on('connection', function (client) {
var id = ++i;
console.log('Client %d connected', id);
function msg (msg) {
console.log("MESSAGE", msg);
}
make_connection(function(msg) {
console.log("MSG", msg);
try {
client.write(msg);
} catch (e) {
console.log("err" + e);
}
});
client.on('message', msg);
});
/**
* Listen.
*/
server.listen(3000, function () {
console.error(' ∞ listening on http://127.0.0.1:3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment