首页 > 编程语言 > 详细

SpringBoot WebSocket实现前后端交互 (转)

时间:2020-11-27 13:56:01      阅读:24      评论:0      收藏:0      [点我收藏+]

原文:https://www.cnblogs.com/xiaozhengtongxue/p/13448778.html

  • websocket: 在浏览器和服务器之间建立TCP连接,实现全双工通信
    springboot使用websocket有两种方式,一种是实现简单的websocket,另外一种是实现STOMP协议。本篇讲述如何使用springboot实现简单的websocket。

直接在pom.xml中导入依赖。

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>

首先注入一个ServerEndpointExporterBean,该Bean会自动注册使用@ServerEndpoint注解申请的websocket endpoint,代码如下:

@Component public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
@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(); } } } }

由于部分浏览器可能不支持,可以先测试,代码如下:

<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>
@Autowired private WebSocket webSocket; @Override @Transactional public OrderDTO create(OrderDTO orderDTO) {//创建订单 。。。。(具体代码省略) //创建新订单 发送websocket消息 webSocket.sendMessage(orderDTO.getOrderId()); return orderDTO; }

添加新订单:
技术分享图片
接收到websocket消息
技术分享图片

技术分享图片



SpringBoot WebSocket实现前后端交互 (转)

原文:https://www.cnblogs.com/lshan/p/14047527.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!