Spring Consolidated WebSocket Application Example (top) _java

Source: Internet
Author: User

The following tutorial is a small series in the development of a company's CRM system, collation of some relevant data, in the system has a lot of message push function, in which the use of websocket technology. The following small compilation to share to cloud Habitat Community Platform for your reference

1. Maven Dependency

 <dependency> <groupId>javax.servlet</groupId> <artifactId>
javax.servlet-api</artifactid> <version>3.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> < version>2.3.0</version> </dependency> <dependency> <groupid>com.fasterxml.jackson.core </groupId> <artifactId>jackson-databind</artifactId> <version>2.3.0</version> </ dependency> <dependency> <groupId>org.springframework</groupId> <artifactId> Spring-websocket</artifactid> <version>4.0.1.RELEASE</version> </dependency> < Dependency> <groupId>org.springframework</groupId> <artifactid>spring-messaging</ Artifactid> <version>4.0.1.RELEASE</version> </dependency> 

2. Spring-servlet Configuration

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
context= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns: websocket= "Http://www.springframework.org/schema/websocket" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http:// Www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http:// Www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http:// Www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd " > ... <!--websocket--> &LT;bean id= "WebSocket" class= "Cn.bridgeli.websocket.WebsocketEndPoint"/> <websocket:handlers> < Websocket:mapping path= "/websocket" handler= "WebSocket"/> <websocket:handshake-interceptors> <bean class= "Cn.bridgeli.websocket.HandshakeInterceptor"/> </websocket:handshake-interceptors> </websocket :handlers> </beans>

Where path corresponds to the path of the preceding segment through the WS Protocol interface

3. Implementation of Handshakeinterceptor

Package cn.bridgeli.websocket;
Import Cn.bridgeli.utils.UserManager;
Import Cn.bridgeli.util.DateUtil;
Import Cn.bridgeli.sharesession.UserInfo;
Import Org.apache.commons.lang.StringUtils;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Org.springframework.http.server.ServerHttpRequest;
Import Org.springframework.http.server.ServerHttpResponse;
Import Org.springframework.web.context.request.RequestContextHolder;
Import org.springframework.web.context.request.ServletRequestAttributes;
Import Org.springframework.web.socket.WebSocketHandler;
Import Org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
Import Java.util.Date;
Import Java.util.Map; /** * @Description: Create handshake (handshake) interface * @Date: 16-3-3/public class Handshakeinterceptor extends Httpsessionhandshakein terceptor{private static final Logger Logger = Loggerfactory.getlogger (handshakeinterceptor.class); @Override public Boolean Beforehandshake (ServerHTTPRequest request, ServerhttpresponSE response, Websockethandler wshandler, map<string, object> attributes) throws Exception {Logger.info ("before shaking up ..."
);
Servletrequestattributes attrs = (servletrequestattributes) requestcontextholder.getrequestattributes ();
UserInfo Curruser = Usermanager.getsessionuser (Attrs.getrequest ());
Usersocketvo usersocketvo = new Usersocketvo ();
String email= ""; if (null!= curruser) {email = Curruser.getemail ();} if (Stringutils.isblank (email)) {email = dateutil.date2string (new Dat
E ());
} usersocketvo.setuseremail (email);
Attributes.put ("Session_user", Usersocketvo);
return Super.beforehandshake (Request, response, Wshandler, attributes); @Override public void Afterhandshake (ServerHTTPRequest request, serverhttpresponse response, Websockethandler
Wshandler, Exception ex) {Logger.info ("Create a handshake ...");
Super.afterhandshake (Request, Response, Wshandler, ex); }
}

Because the old couple is not very understand, so the maximum retention of the original code, which is actually from a single sign-on to remove the current logged-in user, into the Usersocketvo object, put into the map. So next we look at the definition of the Usersocketvo object

4. Definition of Usersocketvo

Package cn.bridgeli.websocket;
Import org.springframework.web.socket.WebSocketSession;
Import java.util.Date;
/**
* @Description: User Socket connection Entity
* @Date: 16-3-7 */public
class Usersocketvo {
private String use REmail; User Mailbox Private Date Connectiontime//////////////////////
Last Request time private date Prerequesttime
Newrequesttime; The new request time
private Date lastsendtime = ();//Next message last Send time
private date lasttasksendtime = new Date ()//Pending processing The last time the task
was sent private websocketsession websocketsession//user-corresponding wssession cache only one
//Getxx and Setxx 
}

One of the most important of these is this websocketsession attribute, which we'll use later

5. Implementation of Websocketendpoint

Package cn.bridgeli.websocket;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.web.socket.CloseStatus;
Import Org.springframework.web.socket.TextMessage;
Import org.springframework.web.socket.WebSocketSession;
Import Org.springframework.web.socket.handler.TextWebSocketHandler;  /** * @Description: WebSocket processing class * @Date: 16-3-3 * * public class Websocketendpoint extends textwebsockethandler{private
Static final Logger Logger = Loggerfactory.getlogger (Websocketendpoint.class);
@Autowired private Newslistenerimpl Newslistener;
@Override protected void Handletextmessage (websocketsession session, TextMessage message) throws Exception {
Super.handletextmessage (session, message);
TextMessage returnmessage = new TextMessage (message.getpayload () + "received at server");
Session.sendmessage (ReturnMessage); /** * @Description: @param session * @throws Exception/@Override public void AF After the connection is establishedTerconnectionestablished (websocketsession session) throws exception{Usersocketvo Usersocketvo = (usersocketvo)
Session.getattributes (). Get ("Session_user"); if (null!= usersocketvo) {usersocketvo.setwebsocketsession (session); if (Wssessionlocalcache.exists (
Usersocketvo.getuseremail ())) {Wssessionlocalcache.remove (Usersocketvo.getuseremail ());}
Wssessionlocalcache.put (Usersocketvo.getuseremail (), usersocketvo);
Newslistener.afterconnectionestablished (Usersocketvo.getuseremail ());
Logger.info ("Socket successfully established connection ...");
Super.afterconnectionestablished (session);
@Override public void afterconnectionclosed (websocketsession session,closestatus status) throws exception{
Usersocketvo Usersocketvo = (usersocketvo) session.getattributes (). Get ("Session_user"); if (null!= usersocketvo) {wssessionlocalcache.remove (Usersocketvo.getuseremail ());} logger.info ("Socket closed successfully ...")
;
Super.afterconnectionclosed (session, status); }
}

6. Implementation of Wssessionlocalcache

 package cn.bridgeli.websocket; import java.io.Serializable; import
Java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
/** * @Description: Local cache websocketsession Instance * @Date: 16-3-7 */public class Wssessionlocalcache implements Serializable {
private static map<string, usersocketvo> Wssessioncache = new hashmap<> (); public static Boolean exists (String useremail) {if (!wssessioncache.containskey (UserEmail)) {return false;}
else{return true;}}
public static void put (String useremail, Usersocketvo usersocketvo) {wssessioncache.put (useremail, usersocketvo);} public static Usersocketvo Get (String useremail) {return wssessioncache.get (useremail);} public static void Remove (Strin G useremail) {wssessioncache.remove (useremail);} public static list<usersocketvo> Getallsessions () {return new
Arraylist<> (Wssessioncache.values ()); }
}

See its implementation, the role is more obvious, to store the latest data for each usersocketvo, in fact, here we websocket the implementation has been completed, but there is a core class (about the business logic of Charlie's Class) has not been implemented, The next spring Consolidation WebSocket application Example (next), we'll see how to implement this class.

Introduction to WebSocket protocol

The WebSocket protocol is an important feature of the web domain defined by the RFC-6455 specification: Full-duplex, that is, two-way communication between the client and the server. It is an exciting feature that the industry has been exploring for a long time, using technologies such as Java applets, XMLHttpRequest, Adobe Flash, ActiveXObject, various comet technologies, server-side sending events, and so on.

You need to understand that before using the WebSocket protocol, you need to use the HTTP protocol to build the initial handshake. This relies on a mechanism to establish HTTP, request protocol upgrades (or protocol conversions). When the server agrees, it responds to HTTP status Code 101, indicating that it agrees to switch protocols. Assuming that the HTTP protocol upgrade request passes through a successful handshake through a TCP socket, both the client and server side can send messages to each other.

The Spring Framework version 4.0 has introduced a new module, the Spring-websocket module. It provides support for WebSocket communications. It is compatible with the Java WebSocket API specification JSR-356, while providing additional functionality.

What scene should use WebSocket

In Web applications, the client and server side need to exchange events at higher frequencies and lower latency for websocket. Therefore WebSocket is suitable for finance, games, collaboration and other application scenarios.
It may not be appropriate for other scenarios. For example, a news subscription needs to display breaking news, which can be used with long polling intervals of several minutes, where the latency is acceptable.
Even in scenarios where low latency is required, long polling techniques should be considered if the number of messages transmitted is low (for example, a scenario for monitoring network failures).

And only in the case of low latency and high-frequency message communication, choosing WebSocket protocol is very suitable. Even in such an application scenario, is it still possible to choose WebSocket communication? Or do you choose Rest http communication?
The answer is based on the requirements of the application. However, it may also be possible to use both techniques to implement the data that needs to be exchanged frequently in websocket, while the rest API is implemented as a procedural business implementation technique. In addition, when a rest API calls for a message to be broadcast to multiple clients, it can also be implemented through a websocket connection.

The Spring Framework provides @controller annotations and @restcontroller annotations, both of which can be used for processing HTTP requests and for processing websocket messages. In addition, the request processing method of Spring MVC, or the request processing method of other applications, makes it easy to use the WebSocket protocol to broadcast messages to all interested clients or designated users.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.