Skip to Content

WebSocket support is now part of the capabilities  in SAP HANA Cloud Platform as a beta feature. You can develop Java Web applications using JSR 356 Java API for WebSocket [1] and deploy on both application runtime containers currently available on the platform, namely Java Web and Java EE 6 Web Profile. With this blog I’ll give you a short overview of the protocol and an example of using WebSocket in Web applications.

The protocol

The WebSocket protocol is full duplex, bi-directional protocol over TCP. It is developed to overcome shortcomings of using HTTP as the main driver of Server Push [2] techniques, where the request/response nature of HTTP has its limitations. WebSocket is more efficient and at the same time simple. The protocol is defined by RFC 6455[3] and has support by all major Web browsers, platforms and other frameworks.

To establish connection between peers, called also endpoints, the protocol defines a handshake mechanism carried over HTTP. The latter is using HTTP “upgrade” to request switching from HTTP to WebSocket. Here is an example of such handshake:

/wp-content/uploads/2013/12/handshake_345096.png

After the handshake is performed the connection between endpoints is established. With this connection anyone from the peers is free to initiate sending messages also called frames. There are three types of frames: control and data frames where the latter can be text or binary data frames. The protocol also defines mechanism for fragmentation when dealing with data messages with bigger sizes.

/wp-content/uploads/2013/12/frames_345097.png

The next example illustrates WebSocket protocol usage by developing and endpoint hosted in Java Web application with a peer in a Web browser.

The application

The standard mechanism for supporting WebSocket endpoints in Java Web applications is defined by JSR 356. Typically the implementation of the JSR is supported by web containers which implement standard defined mechanism for discovery and initialization of the endpoints carried in web archives.  Here is an example that uses annotations support to define an endpoint which is processing text based messages. When such message arrives the endpoint just sends back an echo of the message.


package echo;
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/echoEndpoint")
public class EchoEndpoint {
  @OnMessage public String echo(String msg){
  return "echo: "+msg;
  }
}















This implementation of the endpoint is bundled with a standard Java Web application. When deployed in an environment that provides support for JSR 356, the web archive is searched for endpoint annotations and those are registered by the container. The parameter “/echoEndpoint” is path parameter in the WebSocket URI used for remote endpoint identification. For instance, to access a WebSocket endpoint, the peer that initiates connection should use URI scheme of the following format:


"ws:" "//" host [ ":" port ] path [ "?" query ] – used over regular TCP connections
"wss:" "//" host [ ":" port ] path [ "?" query ] – used over TLS connections






To deploy the echo.war sample on SAP HANA Cloud Platform download the latest Java Web or Java EE 6 Web Profile SDK and use the console client to deploy and start the application.

Here is an example in case you use Java Web SDK:


neo deploy -s echo.war -b echo -h hanatrial.ondemand.com -j 7 -a {<account_name>} -u {<user_name>}












The WebSocket implementation in SAP HANA Cloud Platform requires JRE 7, therefore –j 7 option is mandatory. Otherwise if you deploy the sample on Java Web application runtime container without this option the WebSocket endpoints won’t be supported. If you deploy the example on Java EE 6 Web profile there is no need “-j” option as this application runtime container already runs on top of JRE 7.

After a successful deploy, the application can be started either by the console client or by the Cockpit application.

To test the endpoint you can use a chrome browser with Old WebSocket Terminal[4] extension. Install the extension on chrome and use following WebSocket URI.


wss://echo{account_name}.hanatrial.ondemand.com/echo/echoEndpoint












Don’t forget to adjust the {account_name.} In this example the account name is “p1940287438trial” Press “connect” to establish a WebSocket connection to the endpoint from echo application

/wp-content/uploads/2013/12/terminal_346368.png

Looking into http access log will reveal the WebSocket handshake  GET request and 101 Switching Protocols response.


GET /echo/echoEndpoint HTTP/1.1 101 - 0

Enter text message in the console and press send

/wp-content/uploads/2013/12/console_346369.png

Most probably, there will be two text data frames exchanged over TLS enabled TCP connection between the terminal and the “/echoEndpoint” hosted by the echo Web application.

W3C also provides definition of WebSocket[5] typically used by Web browsers. To use the WebSocket in a browser, you need to supply the WebSocket URI to the implementation and/or have handlers if interested in socket events.

If you request the echo application over https, the welcome page will download a html Web page with a Java script example used to communicate with the application end point.

/wp-content/uploads/2013/12/page_346397.png

Here is the Java script snippet used for connecting to the endpoint.


socket = new WebSocket(ws_url);
socket.onopen = function ()  {
  console.log('WebSocket connection is established');
};












The code for sending the message is following:


function send()  {
  if (socket != null)   {
     var message = document.getElementById('message').value;
     socket.send(message);
     console.log('sent: '+message);
  }  else  {
     alert ('There is no WebSocket connection');
  }
}














And here is the code to receive the message


socket.onmessage = function (messageEvent)  {
  console.log('received: '+messageEvent.data);
  document.getElementById('box').value = messageEvent.data;
};












The code is using onopen and onmessage event handlers of the WebSocket to hook into connection establishment and arrival of a message events.

Conclusion

This blog presented a simple example illustrating WebSocket protocol support by SAP HANA Cloud Platform together with the use in Chrome browser as a connection peer. There are variations in the support of WebSocket by browsers and here [6] you can find more detailed information. JSR 356 is the first edition of the Java API for the WebSocket, where the simplicity of the protocol is conveyed to a simple to use java api. For now the feature is released as beta, hence it cannot be used in a productive environment. Still, you can take it for a spin in your trial account.

  1. https://www.jcp.org/en/jsr/detail?id=356
  2. http://en.wikipedia.org/wiki/Push_technology
  3. http://tools.ietf.org/html/rfc6455
  4. https://chrome.google.com/webstore/detail/old-websocket-terminal/cpopfplgicdljhakjpdochbbiodlgaoc
  5. http://www.w3.org/TR/websockets/
  6. http://caniuse.com/websockets
To report this post you need to login first.

16 Comments

You must be Logged on to comment or reply to a post.

  1. Chris Paine

    Some great detail here. This is something that I’d really like to try out, I really like the idea of “live” data flows coming from HCP without a constant poll loop.

    Real – real-time dashboards. 🙂

    I do wonder though, will there be a limitation in the number of sockets that can be opened in a given app? I guess the memory requirements on the JVM will ensure that there is a certain limit, but wondering if this will be a metric that is limited in the subscription model (number of open websockets) or will it just be about data transferred and memory/CPU as currently? I’m guessing these aren’t things that are worked out. It would be interesting to know the thoughts on this.

    Thanks for making this happen!

    Chris

    (0) 
  2. Vikas Singh

    Thanks for the information. Good to see it on SAP HANA Cloud as well – it is definitely one of the features I was looking for .

    Cheers

    Vikas

    (0) 
  3. Anjali Karaneyo

    Hi,

    I am trying to do the same in the sap hana cloud trial, but I got this error message:

    WebSocket connection to ‘wss://echop057245trial.hanatrial.ondemand.com/echo/echoEndpoint’ failed: Unexpected response code: 404


    I can run it successfully in the Hana local runtime. Any clue ?

    Thanks in advance

    (0) 
    1. Dobromir Zahariev

      Hi Anjali,

      are you sure that your user id is p057245

      Seem to be too short – As far as I know the length is somewhere around 10 digits.

      So as Nikoly wrote – the address have following format:

      wss://echo{account_name}.hanatrial.ondemand.com/echo/echoEndpoint 

      And account name for trial accounts have following format:

      <user id>trial

      Best regards,

      Dobri

      (0) 
  4. Reshma L Raghu

    Hello.

    I created the same project from my hdbstudio and deployed it on cloud.

    However, when I try to connect to: wss://echoi061647trial.hanatrial.ondemand.com/echo/EchoEndpoint

    I always get:

    system: websocket error: wss://echoi061647trial.hanatrial.ondemand.com/echo/EchoEndpoint

    system: connection closed, wss://echoi061647trial.hanatrial.ondemand.com/echo/EchoEndpoint

    What could be the reason?

    Regards,

    Reshma

    (0) 
      1. Reshma L Raghu

        Hello Ervin.

        My chrome browser is set for Auto proxy configuration:

        http://proxy:8083/

        When i try via WebSocket.org

        wss://echoi061647trial.hanatrial.ondemand.com/echo/echoEndpoint

        I get the following failure message:

        ERROR: undefined

        DISCONNECTED

        (0) 
        1. Ervin Szolke

          exactly. Until that delivers error (i.e. your websocket connection is immediately closed actually) your application won’t work either. Review your proxy settings.

          (0) 

Leave a Reply