Implementations of version jdk1.7.0_25, tomcat7.0.47.0, tengine/2.1.1 (nginx/1.6.2), servlet3.0, spring4.2.2
Using MAVEN to import version 3.0+ servlet packages:
<dependency> <groupId>javax.servlet</groupId> <artifactid>servlet-api</ Artifactid> <version>3.0-alpha-1</version></dependency>
Then configure Web. XML to configure the version of XSI to more than 3.0:
<web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee " xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0. XSD " version=" 3.0 ">
To import the Spring Web Socket package:
<dependency> <groupId>org.springframework</groupId> <artifactId> Spring-websocket</artifactid> <version>4.2.2.RELEASE</version></dependency>
Configuration file configuration for Dispatcherservlet in Spirng spring WebSocket handler:
<websocket:handlers allowed-origins= "*" > <websocket:mapping path= "/outer/notice/listen" handler= " Noticemessagehandler "/> <websocket:handshake-interceptors> <bean class=" Com.j.socket.notice.noticemessageinterceptor "/> </websocket:handshake-interceptors> </ websocket:handlers> <websocket:handlers allowed-origins= "*" > <websocket:mapping path= "/outer /notice/sockjs/listen "handler=" Noticemessagehandler "/> <websocket:handshake-interceptors> <bean class= "Com.j.socket.notice.noticemessageinterceptor"/> </websocket:handshake-interceptors > <websocket:sockjs/> </websocket:handlers>
Configure Handler class:
Com.j.socket.notice.noticemessagehandler;
Import Packages
@Component Public classNoticemessagehandlerImplementsWebsockethandler {//Store all current online user sockets//The current userid is key, so a user opens multiple socket pages with only the latest page push messages Private Static Finalmap<string, websocketsession> users =NewHashmap<>(); //This method is called when a socket connection is common@Override Public voidAfterconnectionestablished (websocketsession websocketsession)throwsException {//parameters set in the socket interceptorString userId = Websocketsession.getattributes (). Get ("Socket_user"); Users.put (UserId, websocketsession); } @Override Public voidHandlemessage (websocketsession websocketsession, websocketmessage<?> websocketmessage)throwsException {//The method is called when the front-end sends a message}//when a connection error occurs@Override Public voidHandletransporterror (websocketsession websocketsession, Throwable throwable)throwsException {if(Websocketsession.isopen ()) {websocketsession.close (); } String userId= Websocketsession.getattributes (). Get ("Socket_user"); Users.remove (USERID); }//When the connection is closed@Override Public voidAfterconnectionclosed (websocketsession websocketsession, Closestatus closestatus)throwsException {String userId= Websocketsession.getattributes (). Get ("Socket_user"); Users.remove (USERID); } @Override Public Booleansupportspartialmessages () {return false; }//send a message to a user Public voidsendMessage (TextMessage message, String userId) {websocketsession user=Users.get (userId); if(NULL! = User &&User.isopen ()) { Try{user.sendmessage (message); } Catch(Exception e) {}}} //Bulk send messages to all users Public voidsendMessage (TextMessage message) { for(Websocketsession user:users.values ()) {if(User.isopen ()) {Try{user.sendmessage (message); } Catch(Exception e) {}}} }}
Configure interceptors to fetch user data from requests and store them when websocket links.
Public classNoticemessageinterceptorImplementsHandshakeinterceptor {@Override Public BooleanBeforehandshake (ServerHTTPRequest serverhttprequest, Serverhttpresponse serverhttpresponse, WebSocketHandler Websockethandler, map<string, object> Map)throwsException {if(ServerHTTPRequestinstanceofservletserverhttprequest) {Servletserverhttprequest Request=(servletserverhttprequest) serverhttprequest; String userId= Request.getservletrequest (). GetParameter ("UserId"); if(Stringutils.isnotblank (userid)) {map.put (Constants.socket_user, UserID); return true; } } return false; } @Override Public voidAfterhandshake (serverhttprequest serverhttprequest, Serverhttpresponse serverhttpresponse, WebSocketHandler Websockethandler, Exception e) {}}
Front-end JS code, if the browser does not support the socket will be used SOCKJS so you need to import SOCKJS files according to the situation
var websocket;if(' WebSocket 'in window) {WebSocket=NewWebSocket ("ws://yoururl.com/outer/notice/listen?userid=" +getUserId ());} Else if(' Mozwebsocket 'in window) {WebSocket=NewMozwebsocket ("ws://yoururl.com/outer/notice/listen?userid=" +getUserId ());} Else{websocket=NewSOCKJS ("http://yoururl.com/outer/notice/sockjs/listen?userId=" +getUserId ());} Websocket.onopen=function (evnt) {};var length= 0; Websocket.onmessage=function (evnt) {console.log (length+=evnt.data.length);}; Websocket.onerror=function (evnt) {console.log (evnt);}; Websocket.onclose=function (evnt) {}
Nginx corresponding configuration
map $http _upgrade $connection _upgrade {default upgrade; "'Close;} server {... location~*/(Outer/notice) | (Outer/sockjs/notice)/{proxy_pass http://127.0.0.1:8084;proxy_redirect Off;proxy_set_header X-real-IP $remote _addr;proxy_set_header X-forwarded-For $proxy _add_x_forwarded_for;proxy_set_header Host $http _host;proxy_set_header x-nginx-proxytrue;p roxy_http_version1.1;p roxy_set_header Upgrade $http _upgrade;proxy_set_header Connection"Upgrade";}
Spring websocket Configuration