A websockets to websockets gateway in 20 lines of javascript

published Nov 11, 2014 03:55   by admin ( last modified Nov 11, 2014 03:56 )

I needed to connect a python websockets client to a password protected websockets server written in the go language and running over SSL.

However I couldn't get the python libraries (ws4py, autobahn, twisted) connections to be accepted by the server, so I wrote a websockets to websockets gateway in javascript, or rather I just cobbled it together from example scripts. It connects and authenticates to the go server, tellls that server what kind of channel it is interested in, and broadcasts that to any clients connected to the javascript process. It runs under node.js. The server is called "wss" below and the client "ws":

var WebSocketServer = require('ws').Server;
var fs = require('fs');
var WebSocket = require('ws');

wss = new WebSocketServer({
    port: 8080
});

wss.broadcast = function(data) {
    for (var i in this.clients)
        this.clients[i].send(data);
};
// Load the certificate for the TLS connection
var cert = fs.readFileSync('rpc.cert');
var user = "user";
var password = "a password";

// Initiate the websocket connection.  The certificate is self signed
var ws = new WebSocket('wss://localhost:18344/ws', {
    headers: {
        'Authorization': 'Basic ' + new Buffer(user + ':' + password).toString('base64')
    },
    cert: cert,
    ca: [cert]
});
ws.on('open', function() {
    console.log('CONNECTED');
    ws.send('{"jsonrpc":"1.0","id":"0","method":"notifynewtransactions","params":[true]}');
});
ws.on('message', function(data, flags) {
    wss.broadcast(data);

});
ws.on('error', function(derp) {
    console.log('ERROR:' + derp);
})
ws.on('close', function(data) {
    console.log('DISCONNECTED');
})

Maybe some more tweaking could have got the python code to talk directly to the go server, but sometimes you just have to do the solution for which you can estimate the time it will take for it to be in working order.