1, WebSocket introduction
WebSocket is a protocol for Full-duplex communication provided by HTML5, typically a communication between a browser (or other client) and a Web server. This makes it suitable for highly interactive Web applications, such as timely communication chats.
The websocket protocol is a new network protocol based on TCP. It implements the browser and server Full-duplex (Full-duplex) communication-can be popular interpretation for the server to actively send information to the client.
WebSocket is referenced for the first time in the HTML5 specification as a TCP connection, as a placeholder for a TCP based socket API. [1] The WebSocket Communication protocol was established in 2011 by the IETF as the standard RFC 6455 and is supplemented by RFC7936 specifications.
Excerpt from: Baidu Encyclopedia-websocket 2, Spring+websocket
Spring4.0 has already supported websocket, can go to view the official website.
Official website: Spring WebSocket
Note: This spring+websocket, oneself also is not very familiar with, just recently used to, study a bit, record processing, convenient to avoid taking more detours. 3, configuration environment 3.1, Environment:
Spring-4.0.2.release
java1.7
apache-tomcat-7.0.75
maven Build Project:
Pom.xml:
<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>
SPRINGMVC:
<!--SPRINGMVC begin-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.2.RELEASE</version>
</ dependency>
<dependency>
<groupId>org.springframework</groupId>
< artifactid>spring-context-support</artifactid>
<version>4.0.2.RELEASE</version>
</dependency>
<!--Springmvc end-->
WebSocket:
<!--WebSocket-->
<dependency>
<groupId>org.springframework</groupId>
< artifactid>spring-websocket</artifactid>
<version>4.0.2.RELEASE</version>
</ dependency>
<dependency>
<groupId>org.springframework</groupId>
< artifactid>spring-messaging</artifactid>
<version>4.0.2.RELEASE</version>
</ Dependency>
3.2, Servlet-api
Servlet-api must be 3.0+ to support websocket, so if not, update the jar package.
<dependency>
<groupId>javax.servlet</groupId>
<artifactid>javax.servlet-api </artifactId>
<version>3.1.0</version>
</dependency>
3.3, Web.xml configuration
and Web.xml's namespace to make sure it's 3.0+,
Web.xml
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi=
"Http://www.w3.org/2001/XMLSchema-instance" "
xmlns=" Http://java.sun.com/xml/ns/javaee "
xmlns:web=" http://java.sun.com/xml/ns/javaee/web-app_3_0. xsd "
xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0. xsd "
version=" 3.0 >
<!--WebSocket need Servlet3.0 need Web.xml 3.0 and above, and to configure this-->
< absolute-ordering/>
</web-app>
Code: <absolute-ordering/> Also to be added at web.xml start.
and you must add asynchrony to both the filter and the servlet:
<async-supported>true</async-supported>
For example, the configuration of SPRINGMVC in Web.xml will also be added:
<!--SPRINGMVC configuration start-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
< init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath :springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup >
<async-supported>true</async-supported>
</servlet>
<servlet-mapping >
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--SPRINGMVC configuration end -->
4, service end of the specific implementation
4.1, first create the WebSocket processing class
Mywebsockethandler.java
Package com.cuit.secims.mw.ws;
Import java.util.ArrayList;
Import Java.util.Map;
Import Org.apache.log4j.Logger;
Import Org.springframework.web.socket.CloseStatus;
Import Org.springframework.web.socket.TextMessage;
Import Org.springframework.web.socket.WebSocketHandler;
Import Org.springframework.web.socket.WebSocketMessage;
Import org.springframework.web.socket.WebSocketSession;
Import Com.google.common.reflect.TypeToken;
Import Com.google.gson.Gson; public class Mywebsockethandler implements websockethandler{private static final Logger log = Logger.getlogger (mywe
Bsockethandler.class); Save all user sessions private static final arraylist<websocketsession> users = new arraylist<websocketsession>
(); @Override public void Afterconnectionestablished (Websocketsession session) throws when the connection is ready Exception
{Log.info ("Connect websocket success ...");
Users.add (session); }//Processing information @Override publicvoid Handlemessage (websocketsession session, websocketmessage<?> message) throws Exception {Gs
On gson = new Gson (); Converts the message JSON format through Gson to Map//Message.getpayload (). ToString () Gets the message specific content map<string, object> msg = Gson.
Fromjson (Message.getpayload (). toString (), New typetoken<map<string, object>> () {}.gettype ());
Log.info ("Handlemessage ...") +message.getpayload () + "..." +msg), and the other;
Session.sendmessage (message);
Process message msgcontent message content textmessage TextMessage = new TextMessage (Msg.get ("Msgcontent"). ToString (), true);
Call method (send message to All) sendmsgtoallusers (TextMessage); }//Process exception @Override public void Handletransporterror in Transit (websocketsession session, Throwable Exce ption) throws Exception {//TODO auto-generated Method stub}//Close connection @Override public void afterconnectionclosed (websocketsession SESsion, Closestatus closestatus) throws Exception {log.info ("Connect websocket closed ...");
Users.remove (session); @Override public boolean supportspartialmessages () {//TODO auto-generated method stub retur
n false; //Send information to all users public void Sendmsgtoallusers (websocketmessage<?> messages) throws exception{for (Websocketsession user:users)
{user.sendmessage (message);
}
}
}
The processing class can implement Websockethandler most basic interface, also can implement concrete interface
Such as:
Processing class is processing: Connection start, shutdown, processing information, and other methods 4.2, create a handshake (handshake) interface/Interceptor
Handshakeinterceptor. Java
Package com.cuit.secims.mw.ws;
Import Java.util.Map;
Import Org.springframework.http.server.ServerHttpRequest;
Import Org.springframework.http.server.ServerHttpResponse;
Import Org.springframework.web.socket.WebSocketHandler;
Import Org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; public class Handshakeinterceptor extends httpsessionhandshakeinterceptor{//handshake before @Override public boolean b
Eforehandshake (serverhttprequest request, serverhttpresponse response, Websockethandler Wshandler, map<string, object> attributes) throws Exception {System.out.println ("++++++++++++++++ handshakeintercept
Or:beforehandshake ++++++++++++++ "+attributes);
return Super.beforehandshake (Request, response, Wshandler, attributes); }//Handshake @Override public void Afterhandshake (ServerHTTPRequest request, Serverhttpresponse Res Ponse, Websockethandler Wshandler, Exception ex) {System.out.println ("++++++++++++++++ handshakeinterceptor:afterhandshake ++++++++++++++");
Super.afterhandshake (Request, Response, Wshandler, ex);
}
}
The main function of this is to do something before shaking hands, put what you need into the attributes, and then in the Websockethandler session, take the corresponding value, The specific reference Httpsessionhandshakeinterceptor, here also can implement Handshakeinterceptor interface. 4.3, registration processing class and handshake interface
There are two ways to do this: create a class to implement 4.3.1 using an XML configuration file , create a class Mywebsocketconfig
Package com.cuit.secims.mw.ws;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import ORG.SPRINGFRAMEWORK.WEB.SERVLET.CONFIG.ANNOTATION.ENABLEWEBMVC;
Import Org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
Import Org.springframework.web.socket.WebSocketHandler;
Import Org.springframework.web.socket.config.annotation.EnableWebSocket;
Import Org.springframework.web.socket.config.annotation.WebSocketConfigurer;
Import Org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebMvc @EnableWebSocket public class Mywebsocketconfig extends Webmvcconfigureradapter Implements Websocketconfigurer {@Override public void registerwebsockethandlers (WEBSOCKETHANDLERREGISTR Y registry) {//The foreground can use the WebSocket environment Registry.addhandler (Mywebsockethandler (), "/websocket"). Addinte
Rceptors (New Handshakeinterceptor ()); The front desk can not makeUsing the WebSocket environment, the SOCKJS is used to simulate the connection Registry.addhandler (Mywebsockethandler (), "/sockjs/websocket"). Addinterceptors (NE
W Handshakeinterceptor ()). WITHSOCKJS (); }//WebSocket processing class @Bean public Websockethandler Mywebsockethandler () {return new my
Websockethandler ();
}
}
Note: Do not forget to configure an automatic scan of this type in the SPRINGMVC configuration file
<context:component-scan base-package= "com.cuit.secims.mw.ws"/>
4.3.2, XML configuration Method
Spring-websocket.xml
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc= "Http://www.springframework.org/schema/mvc" Xmlns:cont ext= "Http://www.springframework.org/schema/context" xmlns:aop= "Http://www.springframework.org/schema/aop" xmlns:
tx= "Http://www.springframework.org/schema/tx" xmlns:websocket= "Http://www.springframework.org/schema/websocket" xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/s Chema/beans/spring-beans-4.0.xsd Http://www.springframework.org/schema/mvc Http://www.springfram Ework.org/schema/mvc/spring-mvc-4.0.xsd Http://www.springframework.org/schema/context http://www
. springframework.org/schema/context/spring-context-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.oRg/schema/aop/spring-aop-4.0.xsd Http://www.springframework.org/schema/tx Http://www.springframe Work.org/schema/tx/spring-tx-4.0.xsd Http://www.springframework.org/schema/websocket HTTP://WWW.S Pringframework.org/schema/websocket/spring-websocket-4.0.xsd "> <!--WebSocket processing class--> &
Lt;bean id= "MyHandler" class= "Com.cuit.secims.mw.ws.MyWebSocketHandler"/> <!--handshake interface/Interceptor--> <bean id= "Myinterceptor" class= "Com.cuit.secims.mw.ws.HandshakeInterceptor"/> <websocket:handler s > <websocket:mapping path= "/websocket" handler= "MyHandler"/> <websocket:hand shake-interceptors> <ref bean= "Myinterceptor"/> </websocket:handshake-inte Rceptors> </websocket:handlers> <!--registered SOCKJS--> <websocket:hand
Lers> <websocket:mapping path= "/sockjs/websocket" handler= "MyHandler"/> <websocket:handshake-intercept
ors> <ref bean= "Myinterceptor"/> </websocket:handshake-interceptors> <websocket:sockjs/> </websocket:handlers> </beans>
One of the <websocket:sockjs/> is the way to register SOCKJS.
Note: The namespace in XML is to add spring to WebSocket support:
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns=
"Http://www.springframework.org/schema/beans"
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-4.0.xsd
Http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd ">
5, the implementation of client clients
5.1, page display
index.html
<! DOCTYPE html>