SpringBoot_WebSocket 旧城等待, 2021-10-06 03:00 384阅读 0赞 ### SpringBoot\_WebSocket简单使用 ### * 引入依赖 * 核心代码 * 页面代码示例 # 引入依赖 # <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> # 核心代码 # /** * * webSocket服务端 */ @Component @ServerEndpoint("/webSocket") @Slf4j public class WebSocket { private Session session; private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>(); @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); log.info("连接数:{}", webSocketSet.size()); } @OnClose public void onClose() { webSocketSet.remove(this); log.info("连接数:{}", webSocketSet.size()); } @OnMessage public void onMessage(String message) { log.info("收到客户端发来的消息:{}", message); } public void sendMessage(String message) { log.info("广播消息:{}", message); for (WebSocket webSocket: webSocketSet) { try { webSocket.session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } } /** * websocket配置 * * @author vander * */ @Configuration public class WebSocketConfig { /** * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } # 页面代码示例 # <script> var websocket = null; if('WebSocket' in window) { websocket = new WebSocket('ws://192.168.186.108:8080/webSocket'); }else { alert('该浏览器不支持websocket'); } websocket.onopen = function (event) { console.log('建立连接'); } websocket.onclose = function (event) { console.log('连接关闭'); } websocket.onmessage = function (event) { console.log('收到消息:' + event.data); } websocket.onerror = function () { console.log('websocket通信发生错误!'); } window.onbeforeunload = function () { websocket.close(); } </script>
相关 springbootWebSocket环境搭建 springboot webSocket环境搭建 pom编辑: 添加如下内容: <dependency> <groupId>org.spring 拼搏现实的明天。/ 2022年05月09日 05:06/ 0 赞/ 245 阅读
还没有评论,来说两句吧...