In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "SpringBoot how to achieve WebSocket instant messaging", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "SpringBoot how to achieve WebSocket instant messaging" article.
1. Introduce dependency org.springframework.boot spring-boot-starter-websocket org.projectlombok lombok com.alibaba fastjson 1.2.32 and WebSocketConfig to open WebSocketpackage com.shucha.deveiface.web.config; / * * @ author tqf * @ Description * @ Version 1.0 * @ since 2022-04-12 15:35 * / import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration Import org.springframework.web.socket.server.standard.ServerEndpointExporter; / * Open WebSocket * / @ Configurationpublic class WebSocketConfig {@ Bean public ServerEndpointExporter serverEndpointExporter () {return new ServerEndpointExporter ();}} 3, WebSocketServerpackage com.shucha.deveiface.web.ws; / * * @ author tqf * @ Description * @ Version 2022-04-12 15:33 * / import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component Import org.springframework.web.socket.WebSocketSession; import javax.websocket.*;import javax.websocket.server.PathParam;import javax.websocket.server.ServerEndpoint;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArraySet; @ Component@ServerEndpoint ("/ webSocket/ {userId}") @ Slf4jpublic class WebSocketServer {private Session session; private String userId; / * * static variable to record the current number of online connections. It should be designed to be thread safe. * / private static int onlineCount = 0; private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet (); / * Thread-safe set of the concurrent package, which is used to store the MyWebSocket object corresponding to each client * / private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap () / * to save online user information, create a new list in the method to store [the actual project can be stored in a database or cache depending on complexity] * / private final static List SESSIONS = Collections.synchronizedList (new ArrayList ()) / * establish a connection * @ param session * @ param userId * / @ OnOpen public void onOpen (Session session, @ PathParam ("userId") String userId) {this.session = session; this.userId = userId; webSocketSet.add (this); SESSIONS.add (session); if (webSocketMap.containsKey (userId)) {webSocketMap.remove (userId) WebSocketMap.put (userId,this);} else {webSocketMap.put (userId,this); addOnlineCount ();} / / log.info ("[websocket message] has new connections, total: {}", webSocketSet.size ()) Log.info ("[connection ID: {}] establish connections, current number of connections: {}", this.userId, webSocketMap.size ());} / * * disconnect * / @ OnClose public void onClose () {webSocketSet.remove (this); if (webSocketMap.containsKey (userId)) {webSocketMap.remove (userId); subOnlineCount () } / / log.info ("[websocket message] connection disconnected, total: {}", webSocketSet.size ()); log.info ("[connection ID: {}] disconnect, current number of connections: {}", userId, webSocketMap.size ()) } / * send error * @ param session * @ param error * / @ OnError public void onError (Session session, Throwable error) {log.info ("[connection ID: {}] error cause: {}", this.userId, error.getMessage ()); error.printStackTrace () } / * received message * @ param message * / @ OnMessage public void onMessage (String message) {/ / log.info ("[websocket message] received message from client: {}", message); log.info ("[connection ID: {}] received message: {}", this.userId, message) } / * send message * @ param message * @ param userId * / public void sendMessage (String message,Long userId) {WebSocketServer webSocketServer = webSocketMap.get (String.valueOf (userId)); if (webSocketServer sending null) {log.info ("[websocket message] push message, message= {}", message) Try {webSocketServer.session.getBasicRemote (). SendText (message);} catch (Exception e) {e.printStackTrace (); log.error ("[connection ID: {}] failed to send message, message: {}", this.userId, message, e) * @ param message * / public void sendMassMessage (String message) {try {for (Session session: SESSIONS) {if (session.isOpen ()) {session.getBasicRemote () .sendText (message) Log.info ("[connect ID: {}]] send message: {}", session.getRequestParameterMap (). Get ("userId"), message);} catch (Exception e) {e.printStackTrace () }} / * get current connections * @ return * / public static synchronized int getOnlineCount () {return onlineCount;} / * current connections plus one * / public static synchronized void addOnlineCount () {WebSocketServer.onlineCount++ } / * current connections minus one * / public static synchronized void subOnlineCount () {WebSocketServer.onlineCount--;}} 4, test connections to send and receive messages package com.shucha.deveiface.web.controller; import com.alibaba.fastjson.JSONObject;import com.shucha.deveiface.web.ws.WebSocketServer;import lombok.Data;import lombok.experimental.Accessors;import org.springframework.beans.factory.annotation.Autowired Import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; / * * @ author tqf * @ Description * @ Version 2022-04-12 15:44 * / @ RestController@RequestMapping ("/ web") public class TestWebSocket {@ Autowired private WebSocketServer webSocketServer / * message delivery test * / @ GetMapping ("/ test") public void test () {for (int iTunes 1
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.