springboot 集成websocket
springboot 和websocket 集成
·
websocket 协议,作为对于http 的扩展,解决只能客户端发起请求,服务端被动响应的协议,全双工通信,非常好用,这里说一下springboot 中的实现
具体实现很简单,只有以下三步
添加pom 依赖
无需指定websocket 版本,默认使用springboot 版本
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
添加server 端业务逻辑
这里只实现个简单功能,收到客户端消息后,将收到的内容大写后,再返回给客户端
@Slf4j
@Component
@ServerEndpoint("/info") // 指定websocket 连接的url
public class WebSocketServer {
@OnOpen
public void onOpen(Session session) {
log.info("客户端:{}连接成功",session.getId());
}
@OnClose
public void onClose(Session session) {
log.info("客户端:{}连接断开",session.getId());
}
@OnMessage
public String onMsg(String message,Session session) {
log.info("从客户端:{} 收到<--:{}", session.getId(),message);
String send=message.toUpperCase();
String result="客户:%s您好,来自server 的消息:%s";
result = String.format(result, session.getId(), send);
return "来自server 的消息:" + result;
}
}
添加websocket 配置类
配置类非常简单,将对象交给spring 容器进行处理
@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpoint(){
return new ServerEndpointExporter();
}
}
功能测试
使用在线测试网站
https://www.dute.org/websocket
http://www.websocket-test.com/
测试截图如下,可以正常使用
- 客户端界面1
- 客户端界面2
- 服务端打印内容
2022-05-29 12:13:31.530 INFO 16776 --- [ main] .d.s.w.r.o.CachingOperationNameGenerator : Generating unique operation named: getProductByIdUsingGET_2
2022-05-29 12:13:31.532 INFO 16776 --- [ main] .d.s.w.r.o.CachingOperationNameGenerator : Generating unique operation named: getProductByIdUsingGET_3
2022-05-29 12:13:31.556 INFO 16776 --- [ main] com.kk.MaicaiApplication : Started MaicaiApplication in 2.922 seconds (JVM running for 3.889)
2022-05-29 12:13:52.231 INFO 16776 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-05-29 12:13:52.232 INFO 16776 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-05-29 12:13:52.233 INFO 16776 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2022-05-29 12:13:52.259 INFO 16776 --- [nio-8080-exec-1] com.kk.websocket.WebSocketServer : 客户端:0连接成功
2022-05-29 12:14:04.214 INFO 16776 --- [nio-8080-exec-4] com.kk.websocket.WebSocketServer : 从客户端:0 收到<--:aaaa
2022-05-29 12:14:17.699 INFO 16776 --- [nio-8080-exec-3] com.kk.websocket.WebSocketServer : 客户端:1连接成功
2022-05-29 12:14:23.867 INFO 16776 --- [nio-8080-exec-2] com.kk.websocket.WebSocketServer : 从客户端:1 收到<--:bbbb
2022-05-29 12:14:28.288 INFO 16776 --- [nio-8080-exec-9] com.kk.websocket.WebSocketServer : 客户端:1连接断开
2022-05-29 12:14:31.624 INFO 16776 --- [nio-8080-exec-6] com.kk.websocket.WebSocketServer : 客户端:0连接断开
更多推荐
已为社区贡献1条内容
所有评论(0)