一、前言
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。
二、快速搭建springboot-websocket项目的服务端
1 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2 创建配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3 创建WebSocketServer服务类 用来接收数据
websocket的常用注解只有这5个
@ServerEndpoint注意上下文路径,websocket连接地址
@OnMessage只有第一次加载websocket的时候,会调用,生命周期只有一次
@OnClose只有关闭websocket链接的时候,会调用,生命周期只有一次
@OnMessage每次接收信息的时候,都会调用,调用比较频繁
@OnError发生错误的时候调调用

最低0.47元/天 解锁文章
3225

被折叠的 条评论
为什么被折叠?



