首页IT科技springboot websocket端口(SpringBoot整合WebSocket实现后端向前端发送消息)

springboot websocket端口(SpringBoot整合WebSocket实现后端向前端发送消息)

时间2025-09-10 05:19:05分类IT科技浏览5254
导读:目录...

目录

一                、什么是 websocket 接口

二                         、适用场景

三        、示例代码

3.1            、添加pom.xml依赖

3.2                         、创建WebSokcet配置类

3.3            、创建测试发送消息接口

3.4        、测试webSocket(http://www.jsons.cn/websocket/)

一                         、什么是 websocket 接口

使用 websocket 建立长连接                ,服务端和客户端可以互相通信                         ,服务端只要有数据更新        ,就可以主动推给客户端                。

WebSocket 使得客户端和服务器之间的数据交换变得更加简单            ,允许服务端主动向客户端推送数据                         。在 WebSocket API 中                         ,浏览器和服务器只需要完成一次握手            ,两者之间就直接可以创建持久性的连接        ,并进行双向数据传输        。

在 WebSocket API 中                         ,浏览器和服务器只需要做一个握手的动作                 ,然后    ,浏览器和服务器之间就形成了一条快速通道            。两者之间就直接可以数据互相传送                         。

二                 、适用场景

在业务开发过程中碰到一些异步处理(微信支付    、支付宝支付的支付通知)                        ,跨应用的消息传递            。

当业务执行完毕后                     ,需要将成功的信息投递给前端        。一般情况下都是前端调用后端的http/https接口获取数据,后端想要主动推送消息给前端就需要使用到WebSocket进行前后端的通信                         。

三                        、示例代码

3.1                     、添加pom.xml依赖

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

3.2、创建WebSokcet配置类

@Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } } 3.3                    、创建WebSokcet工具类 @ServerEndpoint(value = "/websocket") @Component public class WebSocketServer { private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class); //静态变量                    ,用来记录当前在线连接数                 。应该把它设计成线程安全的    。 private static int onlineCount = 0; //concurrent包的线程安全Set                         ,用来存放每个客户端对应的MyWebSocket对象                        。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); //与某个客户端的连接会话    ,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session) { this.session = session; //加入set中 webSocketSet.add(this); //在线数加1 addOnlineCount(); log.info("有新连接加入!当前在线人数为" + getOnlineCount()); try { MsgResponseVo userMsgResponseVo = new MsgResponseVo(); userMsgResponseVo.setMsg("SUCCESS"); WebSocketServer.sendInfo(JSON.toJSONString(userMsgResponseVo)); } catch (IOException e) { log.error("websocket IO异常"); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { //从set中删除 webSocketSet.remove(this); //在线数减1 subOnlineCount(); log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("来自客户端的消息:" + message); //群发消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群发自定义消息 */ public static void sendInfo(String message) throws IOException { log.info(message); for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }

3.3                         、创建测试发送消息接口

@GetMapping("/testWebSocket") public ApiRestResponse testWebSocket() throws IOException {         //消息体 MsgResponseVo technicianMsgResponseVo = new MsgResponseVo(); technicianMsgResponseVo.setRole("Technician"); technicianMsgResponseVo.setRoleId(1); technicianMsgResponseVo.setMsg("您的订单已取消"); technicianMsgResponseVo.setMsgStatus("CANCEL_ORDER"); technicianMsgResponseVo.setOrderNo("test");         //发送消息 WebSocketServer.sendInfo(JSON.toJSONString(technicianMsgResponseVo)); return ApiRestResponse.success(); } }

3.4    、测试webSocket(http://www.jsons.cn/websocket/)

在网站中输入ws://ip:端口/webSocket工具类的前缀(ws://127.0.0.1:8080/websocket)

3.5                、前端使用WebSocket监听后端WebSocket地址 ,接收到消息后做下一步业务处理                     。

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
c++定时任务开源框架(【Visual C++】游戏开发笔记之七——基础动画显示(一)定时器的使用) 提升网站访问速度的做法错误的是(如何提高网站访问量的方法)