SpringBoot如何使用WebSocket实现前后端交互
我们都知道http协议只能在浏览器单方面向服务器发起请求时获得响应,然而服务器不能主动向浏览器推送消息,想要实现浏览器的主动推送目前有两种主流的实现方式:
- 轮询:缺点很多,但是实现简单
- websocket: 在浏览器和服务器之间建立TCP连接,实现全双工通信
springboot使用websocket有两种方式,一种是实现简单的websocket,另外一种是实现STOMP协议。本篇讲述如何使用springboot实现简单的websocket。
2|0实现
2|1一、导入依赖
1 2 3 4 | <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> |
2|2二、新建WebSocket配置类,注入Bean
首先注入一个ServerEndpointExporterBean,该Bean会自动注册使用@ServerEndpoint注解申请的websocket endpoint,代码如下
1 2 3 4 5 6 7 | @Component public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } } |
3新进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 | @Component //注册到容器中 @ServerEndpoint ( "/webSocket" ) //接收websocket请求路径 @Slf4j public class WebSocket { //当前连接(每个websocket连入都会创建一个WebSocket实例) private Session session; //定义一个websocket容器存储session,即存放所有在线的socket连接 private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>(); //处理连接建立 @OnOpen public void opOpen(Session session){ this .session = session; log.info( "【有新的客户端连接了】:{}" ,session.getId()); webSocketSet.add( this ); //将新用户加入在线组 log.info( "【websocket消息】有新的连接,总数:{}" ,webSocketSet.size()); } //处理连接关闭 @OnClose public void Onclose(){ webSocketSet.remove( this ); log.info( "【websocket消息】连接断开,总数:{}" ,webSocketSet.size()); } //接受消息 @OnMessage public void onMessage(String message){ log.info( "【websocket消息】收到客户端发来的消息:{}" ,message); } // 群发消息 public void sendMessage(String message) { for (WebSocket webSocket : webSocketSet) { log.info( "【websocket消息】广播群发消息,message={}" ,message); try { webSocket.session.getBasicRemote().sendText(message); } catch (Exception e){ e.printStackTrace(); } } } } |
4客户端实现
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 | <script> var websocket = null ; if ( 'WebSocket' in window){ websocket = new WebSocket( 'ws://localhost:8080/webSocket' ); } else { alert( '当前浏览器不支持websocket消息通知' ); } //连接成功建立的回调方法 websocket.onopen = function (event) { console.log( "ws建立连接成功" ); } //连接关闭的回调方法 websocket.onclose = function (event) { console.log( "ws连接关闭" ); } //接收到消息的回调方法 websocket.onmessage = function (event) { /*setMessageInnerHTML(event.data);*/ // alert("ws接收返回消息:"+event.data); console.log( "服务器返回消息: " + event.data); //弹窗提醒(要用到JQuary,所以要先引入JQuary) 播放音乐 $( '#mymodal' ).modal( 'show' ) } //连接发生错误的回调方法 websocket.onerror = function(event){ alert( 'websocket通信发生错误!' ) } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function() { websocket.close(); } </script> |
5 测试
1 2 3 4 5 6 7 8 9 10 11 12 | @Autowired private WebSocket webSocket; @Override @Transactional public OrderDTO create(OrderDTO orderDTO) { //创建订单 。。。。(具体代码省略) //创建新订单 发送websocket消息 webSocket.sendMessage(orderDTO.getOrderId()); return orderDTO; } |
原文连接地址 https://www.cnblogs.com/xiaozhengtongxue/p/13448778.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2021-04-01 Java的MD5盐值加密,Des加密解密和base64加密解密使用方法
2021-04-01 MD5加密