Spring – Web sockets in Java Development

  johnmorgan        2016-09-13 03:56:54       8,355        0    

Experts of java development team are sharing this article with entire java development community. The purpose behind intending this post is to explain spring – Web sockets as a concept to rest of the world.

Technology: Web socket is the one of the protocol supported by web-browsers and web-servers. It provides the two-way communication between client and server. It is used in any Java application for providing the two way communication between client and server. It opens a connection between client and server, connection will still open after it receiving the response also, whenever the server data is updated the server can send the updated data to client using this open connection. Web sockets will stream the messages on top of TCP port, and also it will send the messages over port 80, so that firewall issues will not come.

It mainly used for showing real-time data to customer like monitoring applications and trading applications etc….

Supported browsers: Majority of the browsers will support web sockets, like Google Chrome, Internet Explorer, Firefox, Safari and Opera etc.

Push Technology: in olden days whenever we want to show the real time data, client will repeatedly send the requests to server to get the updated content, Web socket is one of the protocol which will support the push technology, using this instead of sending several request from client, server will send the data to all client so that load on the server will be decreased. Push technology will use publish/subscribe model to get the updated content.

Establishing the Web socket Connection:

The client will send the first request handshake request to server and the connection will open infinitely.

Sample hand shake request:

GET /websocket HTTP/1.1

Host: http://localhost:8080/

Accept-Encoding: gzip, deflate, sdch

Accept-Language: en-US,en;q=0.8,te;q=0.6

Upgrade: websocket

Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

Cookie: JSESSIONID=C9FBCCB729686F7DD33F18B2B4B12637; COOKIE_SUPPORT=true;             GUEST_LANGUAGE_ID=en_US

Sec-WebSocket-Key: mAgmNIfmCabKiOYwCPGEHw==

Connection: Upgrade

Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==

Sec-WebSocket-Version: 13

Origin: http://localhost:8080

Terminologies used in web sockets:

STOMP: STOMP (simple text-orientated messaging protocol) is one of the protocol for text oriented messages communication. It is the interoperable protocol for asynchronous message passing data between client and servers.

It’s a frame based protocol, which frames the model on HTTP.

STOMP frame consists of command, optional headers and optional body. The default encoding of message body is UTF-8, but it also supports other encoding also. STOMP server is modelled as set of destinations to which messages we want to send. The destination syntax will be vary for different implementations.

It acts as a mediator between STOMP Client and message broker, possible commands that STOMP supports:

CONNECT:

SEND

SUBSCRIBE

UNSUBSCRIBE

BEGIN

COMMIT

ABORT

ACK

NACK

DISCONNECT

The first line in the frame content will be command, followed by headers, the header values will be in the format as : ,followed by new blank line, and then message body ending in a null character.

Connecting to STOMP Server:

Including STOPMP client: if the application is using nodejs then we can include the stompjs as dependency, we can install stomp using nodejs , eg: npm install nodejs.

If the application is not using nodejs then we can include the stomp js using script tags.

https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js

Creating stomp client object:

   Creating stomp client over TCP protocol: we can connect to STOMP server using overTCP method by passing host and port.

     var client = Stomp.overTCP('localhost', 61613);

     Creating stomp over Web socket protocol: we can connect to the STOMP server using web socket protocol.

var client = Stomp.overWS('ws://localhost:61614/stomp');

Creating connection: using create method we can establish the connection and authenticate to server. We need to pass authentication details like username and password to this method.

It also accepts the connection callback and error callback.

client.connect(login, passcode, connectionCallback, exceptionCallback);

Disconnecting to server:

  Client variable has disconnect method for closing the connection, after connection closed client will no longer receives the messages.

Eg: client.disconnect(function(){

});

Heart-beating: STOMP broker accepts the heart-beating enabled by default, the client object has heartbeat object which contain the time after which we want to send the heartbeats to server.

Sending messages to server: STOMP provides SEND command to send the messages to server.

Client. Send ("", {}, "");

First argument will be destination to which we want to send the messages, second argument will be headers that we want to send, and third argument will be the message payload.

Subscribing, Receiving the messages from server:

If we want to get messages from destination, first we need to subscribe the destination.

The method syntax:

var subscription = client.subscribe(destination, callback, { id: subscritionId });

First argument is the message destination where we want to send the message.

Second argument is the callback when subscription is successful,

Third argument is the optional attributes in json format.

Callback is invoked after receiving the message.

Unsubscribing: the subscription object has unsubscribe method, which is used to stop receiving the messages.

subscription.unsubscribe();

Acknowledgment: after receiving the message we can send the acknowledgment to server, using ack method present in message object. Receiving the messages and sending the acknowledgment can done in a transaction. Client object provides begin method to start the transaction.

var transaction = client.begin();

After starting the transaction we can send the messages and receive the messages, send the optional acknowledgment to server, and we can either the commit or abort the transaction.

transaction.commit() or transaction.abort()

Spring Configuration:

Spring 4.0 framework added the web Socket support and it is implemented JSR-356(websocket API), and also it provides various add-on features on top of JSR-356.Spring 4 is supports Websocket using SockJS, and also it supports fallback if the browser doesn`t supports websocket.

Spring Web socket Flow:

For our blog we are using RabbitMQ as message broker, Spring websocket provides the embedded RabbitMQ Service, for production environment we can use the external RabbitMQ instead of embedded RabbitMQ. The Spring application will act as broker between Message System and SockJS client.

Spring websocket Annotations:

·         @Subscribe Mapping: It is used to subscribe the topic, and this annotation marks the method has subscription handler for destination, it will only supports Stomp over messages (SUBSCRIBE frame), the subscription request will does not contain any body. This annotation can be used in combination with @MessageMapping,if this method is not annotated with @SendTo or @SendToUser, the response will directly send to client, without passing to message broker. This type of annotation is used mainly for showing the results in summary page.

·         @MessageMapping:It marks the a controller method as message handler for specified destination.Annonated Handler method need to have any of the below types in any order.

  • org.springframework.messaging.Message: holds the complete message information.
  • Argument annotated with org.springframework.messaging.handler.annotation.Payload holds the message payload, and converting to specify type using org.springframework.messaging.converter.MessageConverter. If this variable is annotated with org.springframework.validation.annotation. Validated annotation then it will validated according to JSR-303 bean validation.
  • Argument annotated with org.springframework.messaging.handler.annotation.Header then extract the header information from message, convert using Message Converter if necessary. If it is of Map type then it will extract all headers.
  • If the method argument is annotated with org.springframework.messaging.handler.annotation.DestinationVariable then it holds the template parameter similar to @pathVariable, and also MessageConverter will convert to specified type if necessary.
  • Principal: It holds the websocket security information like authentication information.

• @Send To: If we specify this annotation to method, the return value of this method will be converted using MessageConverter and it will send to specified destination.

• @SendToUser: it is same as @SendTo but it will only send to specified user if he connected to webscokets.

• @EnableWebSocketMessageBroker: It is main annotation to enable the websocket features, it must be annoted in combination with @Configuration.

WebSocketMessageBrokerConfigurer is the main interface provided by the spring websocket for configurations and also spring websocket provides the abstract implementation of this interface AbstractWebSocketMessageBrokerConfigurer, so that no need to implement all of the interface methods. For customizing the websocket configurations either we can implement the interface or we can extends the AbstractWebSocketMessageBrokerConfigurer class.

Configuring Registry Endpoints:

WebSocketMessageBrokerConfigurer interface is provided registerStompEndpoints method to register the stomp endpoints for websocket.

Eg:

Public void registerStompEndpoints(StompEndpointRegistry registry) {

                        registry.addEndpoint("/watchlist").withSockJS();

            }

/watchlist is stomp for endpoint for connecting to sockjs based websockets,Spring websocket currently supporting with SockJS.

Configuring message Broker endpoints:

WebSocketMessageBrokerConfigurer interface is provided configureMessageBroker method to register the message endpoints and application endpoints, the application endpoints will directly send to webscoket client, will not pass through message system.Spring websocket will comes with embedded messaging server for development.we can use any external messaging system with Spring websocket for publish/subscribing the messages.

Eg:

Public void configureMessageBroker(MessageBrokerRegistry registry) {

                        registry.enableSimpleBroker("/queue/", "/topic/");

                        registry.setApplicationDestinationPrefixes("/stocks");

}

enableSimpleBroker is the method to configure the embedded message system.

Connecting external message broker:

MessageBrokerRegistry has one method enableStompBrokerRelay using which we can configure the external message broker.

Eg:

public void configureMessageBroker(MessageBrokerRegistry registry) {

                        StompBrokerRelayRegistration brokerRelayRegistration =registry.enableStompBrokerRelay("/queue/", "/topic/");

                        brokerRelayRegistration.setClientLogin("");

                        brokerRelayRegistration.setClientPasscode("");

                        brokerRelayRegistration.setRelayHost("");

                        brokerRelayRegistration.setRelayPort();

                        registry.setApplicationDestinationPrefixes("/stocks");

            }

Handling messages: WebSocketHandler is the interface provided by Spring websocket for handling messages. Spring websocket is comes with two types of handlers.

BinaryWebSocketHandler is for handling binary message content like uploads.

TextWebSocketHandler: It is for text based messages.

SockJsWebSocketHandler: it is one more handler provided by spring websocket on top of TextWebSocketHandler for handling SockJS messages. It is used for adding sockjs specific message frames, sending heartbeats and delegating events to other websocketHandlers.

SimpleBrokerMessageHandler: A "simple" message broker that recognizes the message types defined in SimpMessageType, keeps track of subscriptions with the using SubscriptionRegistry and sends messages to subscribers.

StompBrokerRelayMessageHandler: It is handler for contacting with external message broker.it receives the messages and forwarding the messages to external message broker. For each CONNECT frame an independent TCP connection opened, and using session ID message header the message will be identified client and it will uses the existing message channel which is created earlier.

Securing Web sockets:

We can secure the websockets using Spring Security Module, we need to add the Principal method argument so that spring security will take the authorization part, we need to provide the Spring security configuration for authentication. If the websocket connection is secure then we can able to send the message to user using @sendToUser annotation.

Conclusion: Websocket is the protocol which is used for two-way communications, spring has provided implementation using SockJS, framework, using Spring Security we can also secured the Websocket messages.

This article is shared by java development team experts to explain the technology Spring-websockets. If you have any doubt or want to know more about the technology, kindly comment below. 

Code Sample: you can download the sample from github

 

https://github.com/sravan4rmhyd/CompanyRankingMonitor

SPRING  JAVA TECHNOLOGY  JAVA DEVELOPMENT 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

localhost is so famous