In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you how to integrate Springboot with Websocket to actively push messages from the back end to the front end. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
It is believed that there are push messages from the server on the mobile phone, such as some timely news information, this article is mainly to achieve this function, only to demonstrate a basic case. Using websocket technology.
What is websocke
TWebSocket protocol is a new network protocol based on TCP. It realizes the full-duplex communication between the client and the server. as we all know from the computer network, since it is full-duplex, it shows that the server can actively send information to the client. This coincides with our push technology or the function of multi-person online chat.
Why not use the HTTP protocol? This is because HTTP is simplex communication, communication can only be initiated by the client, the client request, the server to deal with, this is too troublesome. So websocket came into being.
Let's start the integration directly using Springboot. The following cases have been successfully tested on my own computer, you can modify them according to your own functions.
Second, integrate websocket1 and environment configuration
Idea 2018 Professional Edition (cracked)
Maven 4.0.0
SpringBoot 2.2.2
Websocket 2.1.3
Jdk 1.8
Let's create a new ordinary Springboot project.
2. Add dependency org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-websocket 2.1.3.RELEASE 3 and modify port number in application.properties file
In a word: server.port=8081
4. Create a new config package, create a WebSocketConfig class 1@Configuration 2public class WebSocketConfig {3 @ Bean 4 public ServerEndpointExporter serverEndpointExporter () {5 return new ServerEndpointExporter (); 6} 7} 5, create a new service package, create a WebSocketServer class @ ServerEndpoint ("/ websocket/ {sid}") @ Component public class WebSocketServer {static Log log= LogFactory.getLog (WebSocketServer.class); / / static variable, which is 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 is used to store the corresponding MyWebSocket object for each client. Private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet (); / / A connection session with a client through which you need to send data to the client private Session session; / / receive sid private String sid= "; / * the method called successfully for connection establishment * / @ OnOpen public void onOpen (Session session,@PathParam (" sid ") String sid) {this.session = session WebSocketSet.add (this); / / add addOnlineCount () to set; / / add 1 log.info to the number of online users ("start listening in a new window:" + sid+ ", the current number of online users is" + getOnlineCount ()); this.sid=sid; try {sendMessage ("connected successfully") } catch (IOException e) {log.error ("websocket IO exception");}} / * * connection close the method called * / @ OnClose public void onClose () {webSocketSet.remove (this); / / remove subOnlineCount () from the set / / online minus 1 log.info ("there is a connection closed! The current number of people online is "+ getOnlineCount ();} / * the method called after receiving the client message * @ param message client sends the message * / @ OnMessage public void onMessage (String message, Session session) {log.info (" receive message from window "+ sid+": "+ message) / / for (WebSocketServer item: webSocketSet) {try {item.sendMessage (message);} catch (IOException e) {e.printStackTrace ();} @ OnError public void onError (Session session, Throwable error) {log.error ("error occurs") Error.printStackTrace ();} / realize that the server actively pushes public void sendMessage (String message) throws IOException {this.session.getBasicRemote (). SendText (message);} / / sends a group custom message public static void sendInfo (String message,@PathParam ("sid") String sid) throws IOException {log.info ("push message to window" + sid+ ", push content:" + message) " For (WebSocketServer item: webSocketSet) {try {/ / here you can set only push to this sid, if it is null, then push all if (sid==null) {item.sendMessage (message);} else if (item.sid.equals (sid)) {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-- Create a new controller package and create the Mycontroller class @ Controller public class MyController {/ / Page request @ GetMapping ("/ socket/ {cid}") public ModelAndView socket (@ PathVariable String cid) {ModelAndView mav=new ModelAndView ("/ socket"); mav.addObject ("cid", cid); return mav } / / push data interface @ ResponseBody @ RequestMapping ("/ socket/push/ {cid}") public String pushToWeb (@ PathVariable String cid,String message) {try {WebSocketServer.sendInfo (message,cid);} catch (IOException e) {e.printStackTrace (); return "push failed";} return "sent successfully" 7. Create a new websocket.html page var socket; if (typeof (WebSocket) = = "undefined") {console.log ("your browser does not support WebSocket");} else {console.log ("your browser supports WebSocket") / / implement the WebSocket object, specify the address of the server to be connected and establish a connection with the port socket = new WebSocket ("ws://localhost:8081/websocket/1"); / / Open event socket.onopen = function () {console.log ("Socket is open") Socket.send ("this is a message from the client" + location.href + new Date ());}; / / get the message event socket.onmessage = function (msg) {console.log (msg.data);} / / close event socket.onclose = function () {console.log ("Socket closed");}; / / error event socket.onerror = function () {alert ("Socket has an error");}}
Now you can see the results by developing servers and web pages. In general, the combination of Springboot2+Netty+Websocket is more commonly used. This is just a basic case where you can change it according to your own needs.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.