SockJS

The SockJS library provides cross-browser JavaScript API to enable low latency, cross-domain communication between the browser and server. It aims to support the following goals:

  • Instead of using the WebSocket instance, the SockJS instance is used
  • It provides APIs that are close to the WebSocket API, both for server as well as client-side APIs
  • Faster communication support
  • JavaScript for client side
  • It comes with some chosen protocols that support cross-domain communication

The following code snippet shows us how to enable the SockJS library support for WebSocketConfigure:

@Override 
public void registerWebSocketHandlers(WebSocketHandlerRegistry  
  registry)  
{ 
    registry.addHandler(myHandler(), "/myHandler_sockjs").setAllowedOrigins("*").withSockJS(); 
} 

We can also configure in XML as follows:

<websocket:handlers> 
  <websocket:mapping path="/myHandler"  
    handler="myHandler_sockjs"/> 
  <websocket:sockjs/> 
</websocket:handlers> 

We can update the Capital demo developed earlier to support SockJS as follows:

  1. Add country_sockjs.jsp in WebContent to use with SockJS like this:
var socket = new SockJS( 
  "http://localhost:8080/Ch10_Spring_Message_Handler 
/webS/myHandler_sockjs"); 
  1. Add MyWebSocketConfigurer_sockjs in the com.packt.ch10.config package to configure WebSocket, as we did earlier. To enable the SockJS support, we have to modify the registerWebSocketHandlers() method, as shown in the preceding configuration using withSockJS().
  2. Run the application and request for country_sockjs.jsp to use SockJS. You can observe the console logs as well.

In the preceding example, we used WebSocket to get the connection and handle the events. The new WebSocket protocol has also been introduced for communication, which we used here. It uses less bandwidth. It has no headers like HTTP, and gives simpler and efficient communication. We can also use STOMP for communication.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.36.141