Springboot websocket 的简单使用
项目结构:
引入依赖:
"org.springframework.boot:spring-boot-starter-websocket", "org.springframework.boot:spring-boot-starter-thymeleaf",
启动类:
public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
消息处理类:
@Service public class MyHandler extends TextWebSocketHandler { @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("成功建立连接"); session.sendMessage(new TextMessage("成功建立socket连接")); session.sendMessage(new TextMessage("发送一波消息")); System.out.println("关闭。。。。。。。。。。。"); session.close(); // 发送完就关闭 System.out.println("关闭成功"); } // 处理客户端发来的信息 @Override public void handleTextMessage(WebSocketSession session, TextMessage message) { System.out.println("0000" + message.getPayload()); WebSocketMessage message1 = new TextMessage("server:" + message); try { session.sendMessage(message1); } catch (IOException e) { e.printStackTrace(); } } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { if (session.isOpen()) { session.close(); } System.out.println("连接出错"); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { System.out.println("连接已关闭:" + status); } @Override public boolean supportsPartialMessages() { return false; } }
拦截器:
public class WebSocketInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Map<String, Object> map) throws Exception { System.out.println("----------------WTF------------------"); if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request; HttpSession session = serverHttpRequest.getServletRequest().getSession(); String sid = serverHttpRequest.getServletRequest().getParameter("sid"); System.out.println("连接参数:sid----->" + sid); if (session != null) { map.put("userId", 4); // 设置参数给session } } return true; } @Override public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) { System.out.println("========什么鬼========="); } }
页面配置
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/mytest").setViewName("/mytest"); } }
Websocket配置
@Configuration @EnableWebSocket public class MyWebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/myHandler").addInterceptors(new WebSocketInterceptor()); } @Bean public WebSocketHandler myHandler() { return new MyHandler(); } }
mytest.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <meta charset="UTF-8"/> <head> <title>Home</title> <script th:src="@{sockjs.min.js}"></script> <script th:src="@{stomp.min.js}"></script> <script th:src="@{jquery.js}"></script> </head> <body> <script type="text/javascript"> function connect() { var ws = new WebSocket("ws://localhost:8090/myHandler?sid=1") ws.onopen = function () { console.log("onpen"); ws.send("{}"); ws.send("哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"); } ws.onclose = function () { console.log("==========================================="); console.log("onclose"); } ws.onmessage = function (msg) { console.log("发消息来了!"); var item = $("#response"); var msg1 = item.html(); item.html(msg1 + " <br/> " + msg.data); console.log(msg.data); } } </script> <div> <button id="connect" onclick="connect();">开始打印</button> </div> <div id="conversationDiv"> <p id="response"></p> </div> </body> </html>
application.properties改了一下端口:
server.port=8090
转载于:https://my.oschina.net/u/3477913/blog/1510212