In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how springboot uses websocket technology to actively send messages to the front end. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Use websocket technology to actively send messages to the front end
SpringBoot2.0 's support for WebSocket is so great that there are packages to introduce directly.
Org.springframework.boot spring-boot-starter-websocket WebSocketConfig
Enabling WebSocket support is also very simple.
Package com.spark.common.config; import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter; / * * @ Author Lxq * @ Date 2021-06-12 17:11 * @ Version 1.0 * enable websocket support * / @ Configurationpublic class WebSocketConfig {@ Bean public ServerEndpointExporter serverEndpointExporter () {return new ServerEndpointExporter ();}} WebSocketServer
This is the point. The core is here.
Because WebSocket is similar to the form of client server (using ws protocol), the WebSocketServer here is actually equivalent to a Controller of ws protocol.
Directly @ ServerEndpoint ("/ socketServer/ {userId}"), @ Component can be enabled, and then implement @ OnOpen to open the connection, @ onClose to close the connection, @ onMessage to receive messages and other methods.
Create a new ConcurrentHashMap webSocketMap to receive the WebSocket of the current userId to facilitate push messages to the userId between IM. Stand-alone version can be achieved here.
Package com.spark.common.utils.websocket; import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.spark.common.utils.StringUtils;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component; import javax.websocket.*;import javax.websocket.server.PathParam;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.util.concurrent.ConcurrentHashMap / * @ Author Lxq * @ Date 2021-06-12 17:13 * @ Version 1.0 * / @ ServerEndpoint ("/ socketServer/ {userId}") @ Component@Slf4jpublic class WebSocketServer {/ * 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 is used to store the MyWebSocket object corresponding to each client. * / private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap (); / * A connection session with a client that is needed to send data to the client * / private Session session; / * receive userId * / private String userId = "" / * * method called successfully for connection establishment * / @ OnOpen public void onOpen (Session session, @ PathParam ("userId") String userId) {this.session = session; this.userId = userId; if (webSocketMap.containsKey (userId)) {webSocketMap.remove (userId); webSocketMap.put (userId, this) / / join set} else {webSocketMap.put (userId, this); / / join set addOnlineCount (); / / number of online plus 1} log.info ("user connection:" + userId + ", the current number of online users is" + getOnlineCount ()); try {sendMessage ("connected successfully") } catch (IOException e) {log.error ("user:" + userId + ", network exception!");}} / * * method called by connection shutdown * / @ OnClose public void onClose () {if (webSocketMap.containsKey (userId)) {webSocketMap.remove (userId) / / remove subOnlineCount () from set;} log.info ("user exit:" + userId + ", the current number of online users is" + getOnlineCount ()) } / * the method called after receiving the client message * * @ param message client sends a message * / @ OnMessage public void onMessage (String message, Session session) {log.info ("user message:" + userId + ", message:" + message)) / / messages can be sent in groups / / messages can be saved to the database, redis if (StringUtils.isNotBlank (message)) {try {/ / parse the sent message JSONObject jsonObject = JSON.parseObject (message); / / append the sender (prevent string modification) jsonObject.put ("fromUserId", this.userId) String toUserId = jsonObject.getString ("toUserId"); / / websocket if (StringUtils.isNotBlank (toUserId) & & webSocketMap.containsKey (toUserId)) {webSocketMap.get (toUserId) .sendMessage (jsonObject.toJSONString ()) delivered to the corresponding toUserId user } else {log.error ("requested userId:" + toUserId + "not on this server"); / / otherwise, send it to mysql or redis}} catch (Exception e) {e.printStackTrace () } / * @ param session * @ param error * / @ OnError public void onError (Session session, Throwable error) {log.error ("user error:" + this.userId + ", reason:" + error.getMessage ()); error.printStackTrace () } / * implement server active push * / public void sendMessage (String message) throws IOException {this.session.getBasicRemote () .sendText (message) } / * send custom message * / public static void sendInfo (String message, @ PathParam ("userId") String userId) throws IOException {log.info ("send message to: + userId +", message: "+ message); if (StringUtils.isNotBlank (userId) & & webSocketMap.containsKey (userId)) {webSocketMap.get (userId) .sendMessage (message)) } else {log.error ("user" + userId + ", not online!") ;}} / * get the current number of online users * * @ return * / public static synchronized int getOnlineCount () {return onlineCount;} / * added * / public static synchronized void addOnlineCount () {WebSocketServer.onlineCount++ } / * reduce the number of people * / public static synchronized void subOnlineCount () {WebSocketServer.onlineCount--;}} basic introduction to websocket-the project structure of sending messages at the front end is as follows
TestSocket.java
Package com.charles.socket; import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint; @ ServerEndpoint (value = "/ helloSocket") public class TestSocket {/ * the method called when a link is established. * @ param session * / @ OnOpen public void open (Session session) {System.out.println ("starting to establish a link..."); System.out.println ("the id of the current session is:" + session.getId ());} / * message processing method. * @ param session * / @ OnMessage public void message (Session session, String data) {System.out.println ("start processing messages..."); System.out.println ("id of the current session is:" + session.getId ()); System.out.println ("data sent from the front-end page is:" + data);}}
The index.jsp code is as follows:
Charles-WebSocket var websocket = null; var target = "ws://localhost:8080/websocket/helloSocket"; function buildConnection () {if ('WebSocket' in window) {websocket = new WebSocket (target);} else if (' MozWebSocket' in window) {websocket = MozWebSocket (target) } else {window.alert ("browser does not support WebSocket");}} / / sends a message to the background server. Function sendMessage () {var sendmsg = document.getElementById ("sendMsg") .value; console.log ("message sent:" + sendmsg); / / sent to the background server. Websocket.send (sendmsg);} message sending
Note:
When interacting with the background, be sure to click: start establishing a connection. You know. Messages cannot be sent without establishing a connection.
Click first, start to establish a connection, and then enter the content in the text box: I am Charles, click on the message to send, looking at the background log.
This is the end of the article on "how springboot uses websocket technology to actively send messages to the front end". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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.