首页 > 学院 > 开发设计 > 正文

springBoot整合webSocket

2019-11-06 08:21:48
字体:
来源:转载
供稿:网友

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")@Componentpublic 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>
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表