Spring Boot项目——Spring Boot配置websocket
步骤
- 引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
- 创建配置
@Configuration public class WebsocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
- 创建service
@Component @ServerEndpoint("/websocket/{userName}") public class WebSocketServiceImpl { private Session session; private static CopyOnWriteArraySet<WebSocketServiceImpl> webSockets =new CopyOnWriteArraySet<>(); private static Map<String,Session> sessionPool = new HashMap<String,Session>(); @OnOpen public void onOpen(Session session, @PathParam(value="userName")String userName) { this.session = session; webSockets.add(this); sessionPool.put(userName, session); System.out.println(userName+"【websocket消息】有新的连接,总数为:"+webSockets.size()); } @OnClose public void onClose() { webSockets.remove(this); System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size()); } @OnMessage public void onMessage(String message) { System.out.println("【websocket消息】收到客户端消息:"+message); } // 此为广播消息 public void sendAllMessage(String message) { for(WebSocketServiceImpl webSocket : webSockets) { System.out.println("【websocket消息】广播消息:"+message); try { webSocket.session.getAsyncRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } // 此为单点消息 public void sendOneMessage(String userName, String message) { System.out.println("【websocket消息】单点消息:"+message); Session session = sessionPool.get(userName); if (session != null) { try { session.getAsyncRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } }
-
- 注意此处@ServerEndpoint注解的值要和前端通信的接口地址保持一致,否则不能连接通信。
-
Websocket Server 已经搭建完成,客户端已经可以和服务端通信了。服务端 向客户端推送消息 通过
session.getBasicRemote().sendText(message)
测试
- 代码如下
@RequestMapping("/websocket") @RestController public class WebSocketController { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private WebSocketServiceImpl webSocketService; @ResponseBody @GetMapping("/sendAllWebSocket") public String test() { String text="你们好!这是websocket群体发送!"; webSocketService.sendAllMessage(text); return text; } @GetMapping("/sendOneWebSocket/{userName}") public String sendOneWebSocket(@PathVariable("userName") String userName) { String text=userName+" 你好! 这是websocket单人发送!"; webSocketService.sendOneMessage(userName,text); return text; } }
-
- 通过url测试通信结果,前端可以打印信息
分类:
Spring Boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」