WebSocket 使用记录
WebSocket 主要解决的问题是 后端数据更新主动像前端推送数据
所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
开启Websocket 支持
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.example.dome; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; import javax.websocket.server.ServerEndpoint; /** * @author SPC-044 * @date 13:39 * @Version 1.0 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } } |
1 | WebSocket 拦截服务类 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | package com.example.dome; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RestController; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.concurrent.ConcurrentHashMap; /** * @author SPC-044 * @date 10:57 * @Version 1.0 */ @ServerEndpoint ( "/webSocket/{id}" ) @RestController public class WebSocket { private static final Logger loger = LoggerFactory.getLogger(WebSocket. class ); private static volatile int onlineCount = 0 ; // private static CopyOnWriteArraySet<WebSocket> webSocketSet =new CopyOnWriteArraySet(); private String id; private static ConcurrentHashMap<String,WebSocket> webSocketMap = new ConcurrentHashMap(); private Session session; @OnOpen public void onOpen(Session session, @PathParam ( "id" ) String id){ //新建连接时调用 this .session=session; this .id =id; webSocketMap.put(id, this ); // webSocketSet.add(this); loger.info( "openWebSocket id={},name={}" ,id); } @OnClose public void onClose(){ //关闭链接时调用 if (webSocketMap.containsKey(id)){ webSocketMap.remove(id); } // webSocketSet.remove(this); loger.info( "closeWebSocket。。。" ); } @OnMessage public void onMessage(String messsge,Session session){ //接受前端消息 loger.info( "收到消息{}" ,messsge); try { // sendMessage(messsge); } catch (Exception e) { e.printStackTrace(); } } @OnError public void onError(Session session,Throwable error){ //链接异常时访问 loger.info( "链接错误" ); } private void sendMessage(String message) throws Exception { if ( this .session.isOpen()){ this .session.getBasicRemote().sendText(message); } } public static void sendInfo(String id,String message){ // 后端主动像前端推消息 if (webSocketMap.get(id) != null && webSocketMap.containsKey(id)){ try { webSocketMap.get(id).sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } else { loger.info( "该用户不在线!" ); } } } |
前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>123</p> <button name="test" value="模拟建立链接" onclick="lianjie()" >test</button> </body> <script type="text/javascript"> // 加载页面时生成随机数模拟不同用户的 Id var id = Math.ceil(Math.random()*10); console.log(id); function lianjie() { send(); } // 加载页面时 建立链接 id 用于区分不同用户 var webSocket = new WebSocket("ws://127.0.0.1:8082/webSocket/"+id); webSocket.onerror = function () { console.log("链接错误"); } webSocket.onopen = function () { console.log("链接成功"); } webSocket.onmessage =function (event) { console.log(event.data); } webSocket.onclose = function () { console.log("关闭链接"); } function closeWebSocket() { webSocket.close(); } function send() { webSocket.send("第一次发消息"); } </script> </html>
后端主动像前端推送消息
WebSocket.sendInfo("10", "id 10 你好"); 传入 用户id 及消息
@RequestMapping("/webSocketTest") public void websocketTest(){ Thread thread = new Thread(() -> { WebSocket.sendInfo("1", "id 1 你好"); }); Thread thread1 = new Thread(() -> { WebSocket.sendInfo("10", "id 10 你好"); }); thread.start(); thread1.start(); }
分类:
webSocket学习记录
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix