springBoot整合webSocket

3/8/2017来源:ASP.NET技巧人气:3180

1、使用注解@ServerEndpoint注解webSocket

@ServerEndpoint("/logWebSocket") public class LogWebSocketHandle { /** * 新的WebSocket请求开启 */ @OnOpen public void onOpen(session session) { } @OnMessage public void onMessage(String message, Session session) { logger.info("---------------->message:"+message); } /** * WebSocket请求关闭 */ @OnClose public void onClose() { } @OnError public void onError(Throwable thr) { thr.PRintStackTrace(); } }

2、在页面创建webSocket链接

var webSocketUrl = "ws://192.168.2.1:8080/webSocketPro/logWebSocket"; var websocket = new WebSocket(webSocketUrl); websocket.onopen = function(e) { //给服务器端发消息 websocket.send('message'); } websocket.onmessage = function(event) { // 接收服务端的消息 var data = event.data; };

3、如果在tomcat下启动springBoot应用,请求webSocket访问404,需要在springBoot应用中注入webSocket配置,同时在webSocket实现类上添加@Component注解

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter (){ return new ServerEndpointExporter(); } } @ServerEndpoint("/logWebSocket") @Component public class LogWebSocketHandle { }

4、springBoot中webSocket依赖的jar包

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>1.4.1.RELEASE</version> </dependency>