WebSocket 协议是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工通信--允许服务器主动发送信息给客户端,实现客户端之间的交互。
WebSocket 是从 Html5 中演化而出,但是相对于 HTTP的 不支持持久性连接,WebSocket 是一个持久化的协议。
实现 WebSocket 协议后,服务端只要与客户端进行过一次连接之后,就不需要再次连接,并且可以一直向客户端发送信息,即服务端主动向客户端发送消息。
由于 WebSocket 协议在握手阶段采用了 HTTP 协议,能通过各种 HTTP 代理服务器。
目前并不是所有的浏览器都实现了 WebSocket,对于没有实现该协议的浏览器,还需要通过 STOMP 协议来完成兼容。
要想在 Spring Boot 项目中应用 WebSocket,首先要在 pom.xml 中加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<!-- Spring security 主要为了点对点时的安全登录,可以不使用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
下面开发一个简单的 WebSocket 服务
· 创建 java 配置文件
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(){