Websocket UDP proxy with Node.js

A few days ago we faced the following problem. We needed to be able to send messages via javascript in browser to UDP based server. But browsers just do not allow you to send UDP packets, and we didn’t want to reimplement the server so it accepts web connections.

So we decided to put a proxy which will accept websocket connections(we couldn’t use an ajax based mechanism since the client code won’t be on the same domain on the server) and forward that data using udp on the server. When the proxy receives a UDP packet from the server it will forward it to the appropriate websocket client. We choose Node.js because we needed a simple and lightweight solution.

We used the ws wbsocket library for node.js. The code for the proxy is simple as that:

var Buffer = require('buffer').Buffer;
var dgram = require('dgram');
var WebSocketServer = require('ws').Server;

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

//The ip & port of the udp server
var SERVER_IP = '10.0.2.4'
var SERVER_PORT = 11000

wss.on('connection', function(ws) {
    //Create a udp socket for this websocket connection
    var udpClient = dgram.createSocket('udp4');

    //When a message is received from udp server send it to the ws client
    udpClient.on('message', function(msg, rinfo) {
        ws.send(msg.toString());
    });

    //When a message is received from ws client send it to udp server.
    ws.on('message', function(message) {
        var msgBuff = new Buffer(message);
        udpClient.send(msgBuff, 0, msgBuff.length, SERVER_PORT, SERVER_IP);
    });
});

Save the file as proxy.js and launch the server by opening a cmd(or terminal) and type in:

node proxy.js

The server should be listening on port 8080, and ready to accept websocket connections. No we can connect to it using websockets at the client side in browser.

var ws = new WebSocket('http://10.0.2.4:8080/');

ws.onmessage = function(evt) {
      console.log('received from server: ' + evt.data);
}

ws.send('some data to be sent to the udp server..');

That’s it. Simple enough!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s