目录
- 一、依赖
- 二、客户端配置
- 三、会话处理程序 ClientStompSessionHandler
- 四、启动
一、依赖
依赖只有一个,版本跟随spring boot版本就行。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、客户端配置
配置包括三部分,一个是基本的websocket客户端配置,另一个是Stomp客户端配置和会话处理。
先看基本的websocket客户端配置:
@Bean
public WebSocketClient webSocketClient() {
List<Transport> transports = new ArrayList<>();
transports.add(new WebSocketTransport(new StandardWebSocketClient()));
transports.add(new RestTemplateXhrTransport());
return new SockJsClient(transports);
}
然后是Stomp客户端配置:
@Bean
public WebSocketStompClient webSocketStompClient(WebSocketClient webSocketClient, StompSessionHandler stompSessionHandler) {
WebSocketStompClient webSocketStompClient = new WebSocketStompClient(webSocketClient);
webSocketStompClient.setMessageConverter(new StringMessageConverter());
webSocketStompClient.connect("http://localhost:6060/pda-message-websocket", stompSessionHandler);
return webSocketStompClient;
}
会话处理配置:
@Bean
public StompSessionHandler stompSessionHandler() {
return new ClientStompSessionHandler();
}
三、会话处理程序 ClientStompSessionHandler
这个类继承了 StompSessionHandlerAdapter,包括下面的抽象方法:
public StompSessionHandlerAdapter() {
}
public Type getPayloadType(StompHeaders headers) {
return String.class;
}
public void handleFrame(StompHeaders headers, @Nullable Object payload) {
}
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
}
public void handleException(StompSession session, @Nullable StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
}
public void handleTransportError(StompSession session, Throwable exception) {
}
我们的ClientStompSessionHandler类中,主要实现:afterConnected,handleFrame,handleException,handleTransportError。
首先来看 afterConnected方法,这个方法的调用在客户端连接完成之后:
@Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
//这里需要自己写逻辑,这里只是简单的演示
logger.info("客户端已连接: headers {}", connectedHeaders);
session.subscribe("/topic/greeting", this);
String message = "hello";
logger.info("客户端发送:{}", message);
session.send("/app/greeting", message);
}
对帧的处理:
@Override
public void handleFrame(StompHeaders headers, Object payload) {
//这里需要自己写逻辑,这里只是简单的演示
logger.info("客户端收到消息:{}",payload);
}
客户端异常处理:
@Override
public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
//这里需要自己写逻辑,这里只是简单的演示
logger.error("客户端错误: 异常 {}, command {}, payload {}, headers {}", exception.getMessage(), command, payload, headers);
}
传输异常处理:
@Override
public void handleTransportError(StompSession session, Throwable exception) {
//这里需要自己写逻辑,这里只是简单的演示
logger.error("客户端传输错误:错误 {}", exception.getMessage());
}
四、启动
public static void main(String[] args) {
new SpringApplicationBuilder(ClientWebSocketSockJsStompApplication.class)
.web(WebApplicationType.NONE)
.run(args);
}
结果如下: