Combining spring and WebSocket to realize the push of message _java

Source: Internet
Author: User
Tags sessions

This article has three main steps

1, the user establishes the WebSocket connection after the login, the default choice websocket connection, if the browser does not support, then uses the SOCKJS to simulate the connection
2. After the connection is established, the service side returns the unread message of the user
3, the service side carries on the related operation, pushes to one user or all user new message related environment Spring4.0.6 (to choose 4.0+), tomcat7.0.55

Websocet Service-side implementation

Websocketconfig.java

@Configuration
@EnableWebMvc
@EnableWebSocket public
class Websocketconfig extends Webmvcconfigureradapter implements Websocketconfigurer {
@Override public
void Registerwebsockethandlers ( Websockethandlerregistry registry) {
Registry.addhandler (Systemwebsockethandler (), "/websocketserver"). Addinterceptors (New Websockethandshakeinterceptor ());
Registry.addhandler (Systemwebsockethandler (), "/sockjs/websocketserver"). Addinterceptors (New Websockethandshakeinterceptor ())
. WITHSOCKJS ();
}
@Bean public
Websockethandler Systemwebsockethandler () {return
new Systemwebsockethandler ();
}
}

Don't forget to configure an automatic scan of this class in a SPRINGMVC configuration file

<context:component-scan base-package= "Com.ldl.origami.websocket"/>

@Configuration
@EnableWebMvc
@EnableWebSocket

These three general meanings are to enable this class to support the @bean loading of beans, and support SPRINGMVC and websocket, not very accurate roughly, try a little bit @enablewebmvc does not add any effect, @ Configuration originally supported Springmvc automatic scans.

Registry.addhandler (Systemwebsockethandler (), "/websocketserver"). Addinterceptors (New Websockethandshakeinterceptor ())

Used to register the WebSocket server implementation class, and the second parameter is to access the WebSocket address

Registry.addhandler (Systemwebsockethandler (), "/sockjs/websocketserver"). Addinterceptors (New Websockethandshakeinterceptor ())
. WITHSOCKJS ();
}

This is the registration method using the SOCKJS

First Systemwebsockethandler.java

public class Systemwebsockethandler implements Websockethandler {private static final Logger Logger; private static FINA
L arraylist<websocketsession> users; static {users = new arraylist<> (); logger = Loggerfactory.getlogger (Systemwebsockethandler.class);} @Autowired PR
Ivate Websocketservice Websocketservice; @Override public void afterconnectionestablished (Websocketsession sessions) throws Exception {Logger.debug ("Connect to
The WebSocket success ... ");
Users.add (session);
String userName = (string) session.getattributes (). get (Constants.websocket_username); if (username!= null) {//query unread message int count = Websocketservice.getunreadnews ((String) session.getattributes (). Get (
Constants.websocket_username));
Session.sendmessage (New TextMessage (count + ""));} @Override public void Handlemessage (websocketsession sessions, websocketmessage<?> message) throws Exception {//
Sendmessagetousers (); @Override public void Handletransporterror (websocketsession session, ThrowableException) throws exception {if (Session.isopen ()) {session.close ();} logger.debug ("WebSocket connection closed ..."
);
Users.remove (session); @Override public void Afterconnectionclosed (websocketsession session, Closestatus Closestatus) throws Exception {Logge
R.debug ("WebSocket connection closed ...");
Users.remove (session);  @Override public boolean supportspartialmessages () {return false;}/** * Send messages to all online users * * @param message/public void Sendmessagetousers (TextMessage message) {for (websocketsession user:users) {try {if (User.isopen ()) {User.sendmessa
GE (message);
The catch (IOException e) {e.printstacktrace ();}} /** * Send messages to a user * * @param userName * @param message/public void Sendmessagetouser (String userName, TextMessage Messa GE) {for (websocketsession user:users) {if User.getattributes (). () (Constants.websocket_username). Equals (USERNAME) {try {if (User.isopen ()) {user.sendmessage (message);}] catch (IOException e) {e.printstacktrace ();} break; }
}
}
}

The relevant content as soon as you can see, we don't have much to explain.

Then Websockethandshakeinterceptor.java

 public class Websockethandshakeinterceptor implements Handshakeinterceptor {private St
atic Logger Logger = Loggerfactory.getlogger (Handshakeinterceptor.class); @Override public boolean beforehandshake (ServerHTTPRequest request, serverhttpresponse response, Websockethandler Wshandler, map<string, Object > Attributes) throws Exception {if (Request instanceof Servletserverhttprequest) {Se
Rvletserverhttprequest ServletRequest = (servletserverhttprequest) request;
HttpSession session = Servletrequest.getservletrequest (). GetSession (false); if (session!= NULL) {//Use UserName to differentiate between Websockethandler for directed sending of message String UserName = (string) session.getattribute (Constants .
Session_username);
Attributes.put (Constants.websocket_username,username);
} return true; @Override public void Afterhandshake (ServerHTTPRequest request, serverhttpresponse response, Websockethandler Wshandler, Exception Exception) {}} 

The main function of this is to obtain the username in the current request and save it to the current Websockethandler in order to determine the corresponding user of Websockethandler, refer to Httpsessionhandshakeinterceptor

User Login Establish WebSocket connection

index.jsp

<script type= "Text/javascript" src= "Http://localhost:8080/Origami/websocket/sockjs-0.3.min.js" ></script >
<script>
var websocket;
if (' WebSocket ' in window) {
WebSocket = new WebSocket ("Ws://localhost:8080/origami/websocketserver");
if (' Mozwebsocket ' in window) {
websocket = new Mozwebsocket ("Ws://localhost:8080/origami/websocketserver");
} else {
websocket = new Sockjs ("Http://localhost:8080/Origami/sockjs/webSocketServer");
}
Websocket.onopen = function (evnt) {
};
Websocket.onmessage = function (evnt) {
$ ("#msgcount"). HTML (<font color= ' red ' > ' +evnt.data+ ' </font >) ")
};
Websocket.onerror = function (evnt) {
};
Websocket.onclose = function (evnt) {
}
</script>

Pay attention to when using SOCKJS

1, the two writing

<script type= "Text/javascript" src= "Http://localhost:8080/Origami/websocket/sockjs-0.3.min.js" ></script >
websocket = new Sockjs (http://localhost:8080/Origami/sockjs/webSocketServer);

2, in Web.xml

<web-app version= "3.0" xmlns= Http://java.sun.com/xml/ns/javaee "xmlns:xsi=" http://www.w3.org/2001/
Xmlschema-instance "
xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee Http://java.sun.com/xml/ns/javaee /web-app_3_1.xsd ">

Version

Web-app_3_1.xsd

These two versions are 3.0+.

And then add it to this servlet.

<async-supported>true</async-supported>
<servlet>
<servlet-name>appServlet< /servlet-name>
<servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class >
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value >classpath*:servlet-context.xml</param-value>
</init-param>
<load-on-startup>1 </load-on-startup>
<async-supported>true</async-supported>
</servlet>

And then all of the filter is also added

<async-supported>true</async-supported>

3. Add dependent dependencies

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-annotations</artifactid>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-core</artifactid>
<version>2.3.1</version>
</dependency>
< dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-databind</artifactid>
<version>2.3.3</version>
</dependency>

Okay, now that the websocket can be set up properly.

Returns messages that are not read by the user

When the connection is established, it enters the Systemwebsockethandler afterconnectionestablished method, the code looks at the top, and takes out the username saved in the Websockethandshakeinterceptor

Use Session.sendmessage (New TextMessage (count + "") after querying the information; go back to the user.

Service-side push message to user

@Controller public
class Admincontroller {
static Logger Logger = Loggerfactory.getlogger ( Admincontroller.class);
@Autowired (required = false)
private Adminservice adminservice;
@Bean public
Systemwebsockethandler Systemwebsockethandler () {return
new Systemwebsockethandler ();
}
@RequestMapping ("/auditing")
@ResponseBody public
String Auditing (httpservletrequest request) {
// The extraneous code omits the
int unreadnewscount = adminservice.getunreadnews (username);
Systemwebsockethandler (). Sendmessagetouser (username, new TextMessage (Unreadnewscount + ""));
return result;
}

Here you can use Sendmessagetouser to push information to a user, or you can use sendmessagetousers to push information to all 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.