SpringBoot使用WebSocket实现前后端交互的操作方法

springboot使用websocket有两种方式,一种是实现简单的websocket,另外一种是实现STOMP协议,本篇讲述如何使用springboot实现简单的websocket,需要的朋友可以参考下

背景

我们都知道http协议只能在浏览器单方面向服务器发起请求时获得响应,然而服务器不能主动向浏览器推送消息,想要实现浏览器的主动推送目前有两种主流的实现方式:

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

实现

一、导入依赖

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

 org.springframework.bootspring-boot-starter-websocket

二、新建WebSocket配置类,注入Bean

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

@Component public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }

三、新建WebSocket服务端,在其中处理websocket逻辑

@Component  //注册到容器中 @ServerEndpoint("/webSocket")  //接收websocket请求路径 @Slf4j public class WebSocket { //当前连接(每个websocket连入都会创建一个WebSocket实例) private Session session; //定义一个websocket容器存储session,即存放所有在线的socket连接 private static CopyOnWriteArraySet 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(); } } } 

四、客户端实现,可以借助FreeMarker模板工具直接写在ftl文件里。

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

五、测试

(项目实现客户创建新订单之后,前台发出提醒)

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

添加新订单:

接收到websocket消息

到此这篇关于SpringBoot使用WebSocket实现前后端交互的操作方法的文章就介绍到这了,更多相关SpringBoot前后端交互内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是SpringBoot使用WebSocket实现前后端交互的操作方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java