WebSocket: Bringing TCP to the browser

The WebSocket standard is almost finalized. However, WebSocket itself is offering “just” a (data) pipe. WebSocket is well suited to bring event- or data-driven applications to the browser. A valid example would a Web UI for a JMS or AMQP application. With help of the Kaazing Gateway this is possible! As said before, you are basically able to bring any TCP- or UDP-based application to the web.

A simple TCP-based echo server

Since the WebSocket client API itself is not enough (to build a “real” application), we need some (existing) backend, or server. A very simple example would be to bring a (TCP) echo server to the browser, via WebSocket:

var net = require('net');

var server = net.createServer(function (socket) {

  // "on data" event listener:
  socket.on('data', function(data) {

    console.log('Got this data: ' + data)

    // Echo:
    socket.write('You said: ' + data);
  });
});

server.listen(1337, '127.0.0.1');

The above code is a VERY simple “EchoServer” that runs on port “1337”. It is in Node.js. The code is borrowed from their website.

Bring it to the Web

To be able to access this TCP server with a WebSocket application you need to add the following configuration to the Kaazing WebSocket Gateway:

<service>
  <accept>ws://localhost:8000/echo</accept>
  <connect>tcp://localhost:1337/</connect>
  <type>proxy</type>
  <cross-site-constraint>
    <allow-origin>*</allow-origin>
  </cross-site-constraint>
</service>

The entry point for the echo server is the ws://localhost:8000/echoURL. The Gateway connects the WebSocket connection to the backend (check the tcp port). The connection to the echo server is straightforward. The following shows a pretty simple JavaScript program, that opens a WebSocket connection in order to send and receive data from the underlying TCP server:

var websocketConnection = new WebSocket("ws://localhost:8000/echo");
websocketConnection.onopen = function(ev) {
	console.log('Connected to the echo service')
};
websocketConnection.onmessage = function(event) {
  var payload = event.data;
  displayEcho(payload);
};
...
websocketConnection.send("Hello Echo Server");
...

This is obviously a simple example, but it clearly shows the power of WebSocket! Give it a try!

If you are interested in HTML5 and WebSocket, check out the Kaazing Gateway! BTW. Kaazing is hiring

Howdy!

Posted in amqp, fun, javascript, kaazing, lifestyle, websocket

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

%d bloggers like this: