由于工作需要,研究了SpringBoot搭建WebSocket双向通信的过程,其他的教程看了许多,感觉讲得太复杂,很容易弄乱,这里我只展示快速搭建过程
SpringBoot-WebSocket
Server
引入SpringBoot集成WebSocket
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置WebSocketServerConfig
@Configuration
@EnableWebSocket
public class WebSocketServerConfig implements WebSocketConfigurer {
@Bean
public WebSocketHandler webSocketHandler() {
return new WebSocketServerHandler();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry
.addHandler(webSocketHandler(), "/ws")//添加处理器并指定WebSocket的endpoint端点
.setAllowedOrigins("*"); //允许跨域访问
}
}
配置WebSocketServerHandler
@Slf4j
public class WebSocketServerHandler extends TextWebSocketHandler {
/**
* 处理连接后的逻辑
* @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
log.info("Server: WebSocket connection established");
}
/**
* 处理客户端发送的消息
* @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
* @param message:客户端发送的文本消息
*/
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
log.info("Server: Received message: " + message.getPayload());
session.sendMessage(new TextMessage("Server: Hello, client!"));
}
}
Client
引入SpringBoot集成WebSocket
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置WebSocketClientConfig
/**
* WebSocket客户端配置
* @author Lenovo
* @date 2023/11/22
*/
@Configuration
@EnableScheduling
public class WebSocketClientConfig {
@Bean
public WebSocketClientHandler myWebSocketClientHandler() {
return new WebSocketClientHandler();
}
}
配置WebSocketClientHandler
@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "websocket")
public class WebSocketClientHandler extends StandardWebSocketClient implements WebSocketHandler {
private WebSocketSession session;
private String url;
/**
* 连接WebSocket服务端
*/
// @Scheduled(fixedDelay = 60000) // 每隔1分钟连接一次
public void connect() throws Exception {
WebSocketClient client = new StandardWebSocketClient();
session = client.doHandshake(new WebSocketClientHandler(), url).get();
log.info("Client: WebSocket connection established");
}
/**
* 关闭WebSocket连接
*/
@PreDestroy
public void close() throws Exception {
session.close();
}
/**
* @param message:向服务端发送的消息
*/
public void sendMessage(String message) throws Exception {
session.sendMessage(new TextMessage(message));
}
// @Scheduled(fixedDelay = 5000)
// public void sendMessage() throws Exception {
// session.sendMessage(new TextMessage("message"));
// }
/**
* 处理连接后的逻辑
* @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
log.info("Client: WebSocket connection established");
}
/**
* 处理客户端发送的消息
* @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
* @param message:客户端发送的文本消息
*/
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
log.info("Client: Received message: " + message.getPayload());
session.sendMessage(new TextMessage("Client: Hello, server!"));
}
/**
* 处理发生的错误
* @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
* @param exception:通信出现的异常
*/
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
log.info("Client: Error Occurred: " + exception.getMessage());
}
/**
* 连接关闭
*/
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
log.info("Client: Connection Closed");
}
/**
* 用于判断服务器或客户端是否支持分片消息partial message
* WebSocket 协议规范要求所有的 WebSocket 实现都必须支持接收和处理完整的消息
* @return boolean
*/
@Override
public boolean supportsPartialMessages() {
return false;
}
}
这样就完成了整个搭建过程