因为没有基础,不知道从哪里入手。
文档里的例子,https://github.com/rstoyanchev/spring-websocket-portfolio,这个除了WebSocket,还整了Security的东西(坑,版本更新导致默认的passwordEncoder不能用了,不然login一直不成功)
自己写了个乞丐版,体验一下到底怎么运行起来的。
要做啥
客户端:HTML,请求建立连接,显示接收到的消息
服务端:SpringBoot的WebSocket starter,每隔0.5秒发送一个数字
实现
客户端:
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>Test WebSocket</title> <script> var ws = new WebSocket("ws://localhost:8080/myHandler"); ws.onopen = function () { var ele=document.getElementById(‘wsStatus‘); ele.innerHTML="WebSocket状态:已连接"; }; // 接收服务端数据时触发事件 ws.onmessage = function (evt) { var received_msg = evt.data; console.info(received_msg); var ele=document.getElementById(‘countId‘); ele.innerHTML="接收到:"+received_msg; }; // 断开 web socket 连接成功触发事件 ws.onclose = function () { var ele=document.getElementById(‘wsStatus‘); ele.innerHTML="WebSocket状态:已断开"; }; </script> </head> <body> <div> <h2 id="wsStatus">WebSocket状态:</h2> </div> <div > <h2 id="countId">接收到:</h2> </div> </body> </html>
服务端:
1. 从start.spring.io上生成一个初始的Gradle项目,依赖项加入WebSocket。
2. 根据4.2.1, 添加一个handler,每500ms发送一个数字。
package com.fzh.sbootwebsocket.handlers; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; public class MyHandler extends TextWebSocketHandler{ @Override public void handleTextMessage(WebSocketSession session, TextMessage message){ System.out.println("session:"+session.getId()+", Message: "+message.getPayload()); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { for(int i=0;i<100;i++){ TextMessage message = new TextMessage(String.valueOf(i)); session.sendMessage(message); Thread.sleep(500); } } }
3. 将handler配置到路径/myHandler。注意,setAllowedOrigins("*")这个一定要加上,要不然客户端没有响应。
package com.fzh.sbootwebsocket.config; import com.fzh.sbootwebsocket.handlers.MyHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/myHandler").setAllowedOrigins("*"); } @Bean public WebSocketHandler myHandler(){ return new MyHandler(); } }
4. 命令行输入: ./gradlew bootRun
5. 用浏览器打开最开始编辑好的网页,当当当当当!
原文地址:https://www.cnblogs.com/zhsmtp/p/9716065.html
时间: 2024-10-10 09:50:51