springboot整合WebSocket 清疚 2023-06-21 13:27 2阅读 0赞 1、在pom.xml中添加依赖包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency> 2、创建WebSocket配置类(WebSocketConfig.java ) package com.jeff.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * * @description: WebSocket配置 * @author: Jeff * @date: 2019年12月12日 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { System.out.println("SpringBoot 注册 WebSocket"); return new ServerEndpointExporter(); } } 3、创建ws协议的Controller(WebSocketFloorServer.java) package com.jeff.controller; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; @Component @ServerEndpoint("/websocket/{floorId}/floor.do") public class WebSocketFloorServer { // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象 private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<>(); private static final String FLOOR_ID = "floorId"; /** * * @description: 连接建立成功调用的方法 * @author: Jeff * @date: 2019年12月12日 * @param floorId 楼层id * @param session 与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(@PathParam("floorId") String floorId, Session session) { // session 最大空闲时间为10分钟。 session.setMaxIdleTimeout(TimeUnit.MINUTES.toMillis(10)); session.getUserProperties().put(FLOOR_ID, floorId); webSocketSet.add(session); // 加入set中 System.out.println("楼层:" + floorId + "新建连接,当前连接数为:" + getOnlineCount()); } /** * * @description: 连接关闭调用的方法 * @author: Jeff * @date: 2019年12月12日 * @param session */ @OnClose public void onClose(Session session) { String floorId = (String) session.getUserProperties().get(FLOOR_ID); webSocketSet.remove(session); // 从set中删除 System.out.println("楼层:" + floorId + "关闭连接,当前连接数为:" + getOnlineCount()); } /** * * @description: 收到客户端消息后调用的方法 * @author: Jeff * @date: 2019年12月12日 * @param message 客户端发送过来的消息 * @param session */ @OnMessage public void onMessage(String message, Session session) { if (webSocketSet.contains(session)) { String floorId = (String) session.getUserProperties().get(FLOOR_ID); System.out.println("楼层:" + floorId + " 的消息:" + message); } } /** * * @description: 通过楼层id发送消息 * @author: Jeff * @date: 2019年12月12日 * @param message * @param floorId */ public void sendMessage(String message, String floorId) { if (getOnlineCount() != 0) { try { for (Session item : webSocketSet) { if (floorId.equals(item.getUserProperties().get(FLOOR_ID))) { item.getBasicRemote().sendText(message); System.out.println("发送消息:" + message); } } } catch (Exception e) { System.out.println(e.getMessage()); } } } public int getOnlineCount() { return webSocketSet.size(); } } 4、创建测试controller(FloorController.java) package com.jeff.controller; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; @RestController @RequestMapping("floor") public class FloorController { @Autowired private WebSocketFloorServer socketFloorServer; @RequestMapping("hello") public String hello(String floorId) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "Jeff"); map.put("age", 18); map.put("currentDate", new Date()); socketFloorServer.sendMessage(JSONObject.toJSONString(map), floorId); return "HelloWord"; } } 5、打开websocket测试工具连接 ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTczOTcyMA_size_16_color_FFFFFF_t_70] ![在这里插入图片描述][20191212235530701.png] 6、打开浏览器测试,访问 **http://localhost:8080/floor/hello?floorId=1** ![在这里插入图片描述][20191212235623716.png] ![在这里插入图片描述][20191212235718494.png] ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTczOTcyMA_size_16_color_FFFFFF_t_70 1] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTczOTcyMA_size_16_color_FFFFFF_t_70]: https://img-blog.csdnimg.cn/20191212235409401.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTczOTcyMA==,size_16,color_FFFFFF,t_70 [20191212235530701.png]: https://img-blog.csdnimg.cn/20191212235530701.png [20191212235623716.png]: https://img-blog.csdnimg.cn/20191212235623716.png [20191212235718494.png]: https://img-blog.csdnimg.cn/20191212235718494.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTczOTcyMA_size_16_color_FFFFFF_t_70 1]: https://img-blog.csdnimg.cn/20191212235651171.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTczOTcyMA==,size_16,color_FFFFFF,t_70
还没有评论,来说两句吧...