Implement (background Active) message push using the spring boot +websocket

Source: Internet
Author: User
Tags sessions

the use of this webscoket must ensure that the production environment is compatible/supported. Use this webscoket to ensure that the production environment is compatible/supported. Use this webscoket to ensure that the production environment is compatible/supported. The main is tomcat compatibility and support.

There is a need: The app user generates an operation that needs to be perceived by some people in the backend management system (shown as a page message).

The earliest version is the background management system rotation, every once in a while rotation, because the message is important, every few seconds to check. This is obviously very indecent. Consumes a lot of resources and most of the requests are useless (no data is available) and they are very blue and thin.

Later, I wanted to use the message to push the way to deal with this logic. The user creates a target operation in the app, which generates a message that is pushed to the corresponding user in the backend management system.

Then I looked for a variety of materials, a colleague recommended DWZ, and later found that it was not very suitable for the current project (maybe I just don't know how to implement it).

Later learned that websocket, the Internet read a lot of documents are similar to chat room scenes, some different. In this, I mainly focus on the introduction of the server under the active push , by the service side to trigger.

WebSocket main achievable scenarios:

1, web chat room

2, Server message real-time notification

There should be a lot of WebSocket using the tomcat8+h5 environment under the introduction.

PS: My own test environment is TOMCAT7 This is not the case. wang115032337 "https://blog.csdn.net/wang115032337" this friend in his environment, TOMCAT7/8 can use the writing of this article, but need to remove Websocketconfig class (there are articles that TOMCAT7 and 8 support for the websocket is different, I do not understand)

Words do not say, directly on the code, want to know more about WebSocket, please refer to the relevant introduction.

1.pom

	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId> Spring-boot-starter-websocket</artifactid>
        </dependency>
2. The use of @serverendpoint to create WebSocket endpoint ( wang115032337 This friend in his environment to join the @serverendpoint class will error, directly delete the still available

@Configuration public
class Websocketconfig {
    @Bean public
    Serverendpointexporter Serverendpointexporter () {return
        new Serverendpointexporter ();
    }

}
3. Specific implementation class You can choose your own URL or you want to take parameters
Package com.star.manager.service;
Import java.io.IOException;

Import Java.util.concurrent.CopyOnWriteArraySet;
Import Javax.websocket.OnClose;
Import Javax.websocket.OnError;
Import Javax.websocket.OnMessage;
Import Javax.websocket.OnOpen;
Import javax.websocket.Session;

Import Javax.websocket.server.ServerEndpoint;

Import lombok.extern.slf4j.Slf4j;
Import org.springframework.stereotype.Component; @Slf4j//@ServerEndpoint ("/websocket/{user}") @ServerEndpoint (value = "/websocket")@Componentpublic class Websocketserver {//static variable, used to record the current number of online connections.
    It should be designed to be thread-safe.
    private static int onlinecount = 0; The thread-safe set of the concurrent package, which holds the corresponding Mywebsocket object for each client. private static copyonwritearrayset<websocketserver> Websocketset = new Copyonwritearrayset<websocketserver

    > ();

    A connection session with a client, which needs to be sent to the client to send the data private sessions;
        /** * Connection to establish a successful call to the method * * @OnOpen public void OnOpen (Session sessions) {this.session = session;     Websocketset.add (this);           Add Addonlinecount () to the set; Online number plus 1 log.info ("There is a new join.")
        Current online number is "+ Getonlinecount ()");
        try {SendMessage ("Connection succeeded");
        catch (IOException e) {log.error ("WebSocket io exception"); }/////@OnOpen//public void OnOpen (@PathParam (' user ') String user, Session session) {//Currentus
	er = user; System.out.println ("Connected ...")
	"+ Session.getid ());  /** * Connection Shutdown method of call/@OnClose public void OnClose () {websocketset.remove (this);           Deletes the Subonlinecount () from the set; Number of online minus 1 log.info ("There is a connection closed.")
    Current online number is "+ Getonlinecount ()");
}
    /** * The method called after receiving the client message * * @param messages sent over message by the client * * @OnMessage public void OnMessage (String me

        Ssage, Session session) {Log.info ("messages from the client:" + message);
            Mass messages for (Websocketserver Item:websocketset) {try {item.sendmessage (message);
            catch (IOException e) {e.printstacktrace (); }}/** * * @param session * @param error/@OnError public void OnError
        , throwable error) {log.error ("error occurred");
    Error.printstacktrace ();


 }Public void SendMessage (String message) throws IOException {This.session.getBasicRemote (). SendText (Messag e); The/** * Group originates from the definition message */public static void Sendinfo (String message) throws IOException {Log.info (Me Ssage); for (Websocketserver Item:websocketset) {try {item.sendmessage (message); catch (IOException e) {continue; } } }public static synchronized int Getonlinecount () {return onlinecount;
    public static synchronized void Addonlinecount () {websocketserver.onlinecount++;
    public static synchronized void Subonlinecount () {websocketserver.onlinecount--; }
}

generate a message : There are a variety of message scenarios, HTTP (s), timed tasks, MQ, and so on, which is labeled with a HTTPQ requested controller code

	 @RequestMapping (value= "/pushvideolisttoweb", Method=requestmethod.post,consumes = "Application/json") Public
	 @ Responsebody map<string,object> pushvideolisttoweb (@RequestBody map<string,object> param) {
		 Map< string,object> result =new hashmap<string,object> ();
		 
		 try {
			 Websocketserver.sendinfo ("New Customer Inbound, Sltaccountid:" +commonutils.getvalue (param, "Sltaccountid"));
			 Result.put ("Operationresult", True);
		 } catch (IOException e) {
			 result.put ("Operationresult", True);
		 }
		 return result;
	 }


Important place I have been bold, mainly this paragraph, using this method, you can implement the server to push.

    public void SendMessage (String message) throws IOException {
        this.session.getBasicRemote (). SendText (message);
    

4.js (HTML will not write, just find a can trigger this JS can)

//socket = new WebSocket ("ws://localhost:9094/starmanager/websocket/John");
		var socket;
		if (typeof (WebSocket) = = "undefined") {Console.log ("Your browser does not support WebSocket");
			
			}else{console.log ("Your browser supports WebSocket"); Implements the WebSocket object, specifying the server address to connect to the port to establish a connection//socket = new WebSocket ("ws://localhost:9094/starmanager/websocket/John") 
			Socket = new WebSocket ("Ws://localhost:9094/starmanager/websocket");
			Open Event
			Socket.onopen = function () {
				Console.log ("Socket is open");
				Socket.send ("This is the message from the client" + Location.href + new Date ());
			Gets the message event
			socket.onmessage = function (msg) {
				console.log (msg.data);
				Find the message into the    background to get
				getcallinglist ();
			Shutdown Event
			socket.onclose = function () {
				console.log ("socket closed");
			An error event has occurred
			socket.onerror = function () {
				alert ("Error occurred with socket");
			}
			 $ (window). Unload (function () {
				  socket.close ();
				});                            		$ ("#btnSend"). Click (function () {
//                            			Socket.send ("This is the message from the client" + Location.href + new Date ());
//                            		});
//                            		$ ("#btnClose"). Click (function () {
//                            			socket.close ();
//                            		});
		}
                                

Simply put:

Through the front-end Code

Socket = new WebSocket ("Ws://localhost:9094/starmanager/websocket");

Where Starmanager is the project name,/webscoket is the access path name

Establishing a connection, the front-end call Scoket.open () causes the background to add an element to the static member variable Websocketset , which is equivalent to a cache . Background service Call SendMessage

(Specify a user, directed) or Sendinfo (Traverse websocketset to send, like a mass) method, you can push messages to the Logged-on client.

So much for the code. I'm going to run with these codes. Do when the page reported 404 error, if it is spring boot+h5, carefully check and I code there is no difference, plus the configuration path is OK, the problem should not be small.


If you happen to have a similar scenario that can be implemented with websocket, hopefully it will help you. If you have written incorrectly or not good enough, please correct me.









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.