Over a million developers have joined DZone.

WebSocket with Jaggery (JaggeryJS Sample)

· Integration Zone

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA Technologies.

My last Post was "how Web Socket Implementation in Tomcat 7 and Jaggery[4]". Now we will write simple app with using jaggeryjs webSocket.
Here I will give some

  • Basic information on web socket
  • Sample javaScript (Front end) code samples
  • Handling cross-domain in web sockets
  • WebSocket spec and types that support over it
  • Where to use web sockets with web socket top level architecture
  • webSocket using sample with jaggery[5]


WebSocket protocol within the browser (JS)

firstly you need define a JavaScript API for the WebSocket protocol within the browser, allowing bi-directional communication between the browser and server.

you can defines new protocols, ws:// and wss:// for standard and secure WebSocket connections:

//connection URL

var connection = new WebSocket('ws://subdomain.examnple.com/some-endpoint')

//web socket events

connection.onopen = function(e) {
  console.log("Connected");
};

connection.onmessage = function(e) {
  console.log( "Received: " + e.data);
};

connection.onclose = function(e) {
  console.log("Connection closed");
};

cross-domain

WebSockets is cross-domain by default and it is up to you to optionally restrict domain access on server via Origin header:

Access-Control-Allow-Origin: http://websocket.org
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type

Built-in method for defining WebSocket extensions via RFC, Current extensions include perframe-deflate[1] and multiplexing[2]. Original WebSocket spec allowed for strings But now also allows buffered arrays and blobs

var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
  binary[i] = img.data[i];
}
connection.send(binary.buffer);

var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);

[NOTE]

WebSocket Doesn't support sending/receiving JSON (yet), But can be accomplished by serializing/deserializing[3]:

wss.on('connection', function(ws) {
  ws.send(JSON.stringify({
    attribute: 'connected'
  }));
});

client

connection.onmessage = function (e) {
  var response = JSON.parse(e.data);
};

Where can we use WS?

  • Browser-to-server
  • Not really meant for server-to-server communication; better off using UDP or some other low-overhead transfer protocol if you control both servers
  • Not meant for browser-to-browser communication; that's what WebRTC is for
  • Used ‘wss’ in production

Top level architecture

image

Example real-world uses

  • Real-time chat application
  • Multi-player HTML5 game
  • Event-based in-page analytics

Server can be built in any language, which supports event loop

Jaggery Sample

Now jaggery have power to handle full web socket API over js. You develop front end js (client) upon on webSocket specification[7].

Here is server.jag sample:

<%
var log = new Log();


webSocket.ontext = function (data) {
    log.info('Client Sent : ' + data);   
};

webSocket.onbinary = function (stream) {
    log.info('Client Streamed : ' + stream.toString());
};


webSocket.onopen = function (outstre) {
    log.info('Connection open');

};

webSocket.onclose = function (status) {
    log.info('Client Streamed close');
   
};

%>

Now you can try to develop chat room sample (Very well known sample for socket). Jaggery server will to broadcast the message that we get for app the client that is connected for server app via web socket.

image

Here is server.jag source[8] front end client source code also[8].Here is screen shoot of testing.

image

[1] http://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate-05
[2] http://tools.ietf.org/html/draft-ietf-hybi-websocket-multiplexing-10
[3] https://developer.mozilla.org/en/docs/WebSockets/Writing_WebSocket_client_applications
[4] http://madhukaudantha.blogspot.com/2014/02/jaggery-socket-implementation-in-tomcat.html
[5] http://madhukaudantha.blogspot.com/search/label/Jaggery
[6] http://www.html5rocks.com/en/tutorials/websockets/basics/

[7] http://dev.w3.org/html5/websockets/

[8] https://github.com/Madhuka/MadhukaBlogRepo/tree/1.0.0/SampleApps/JaggeryApps/chatroom

The Integration Zone is brought to you in partnership with CA Technologies.  Use CA Live API Creator to quickly create complete application backends, with secure APIs and robust application logic, in an easy to use interface.

Topics:

Published at DZone with permission of Madhuka Udantha, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}