如何正确实现spring-websocket java客户端

时间:2015-02-03 16:52:28

标签: java spring spring-websocket

我正在为我的WebSocket服务器开发一个Spring WebSocket Stomp Client,我收到了相互矛盾的信息。 我找到了两种方法让它工作,而没有太多细节,我想知道哪种方式被认为是实现客户端的“正确”方式。

有人可以帮我理解WebSocketConnectionManager的用途吗?

另外,还有一个问题,我如何保持websocket连接打开,程序运行以接受新消息,而不必编写System.in.read()行。

第一种方式:直接使用SockJsClient

URI uri = new URI("ws://localhost:8080/stomp");
StandardWebSocketClient simpleWebSocketClient = new StandardWebSocketClient();

List<Transport> transports = new ArrayList<>(1);
transports.add(new WebSocketTransport(simpleWebSocketClient));

SockJsClient sockJsClient = new SockJsClient(transports);
sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec());

StompMessageReceiver messageHandler = new StompMessageReceiver();
StompWebSocketHandler websocketHandler = new StompWebSocketHandler(messageHandler, new StringMessageConverter());

try {
    this.webSocketClient.doHandshake(websocketHandler, null, uri).get();
} catch (InterruptedException | ExecutionException e) {
    throw new IllegalStateException(e);
}

System.in.read();

第二种方式:使用WebSocketConnectionManager

StandardWebSocketClient simpleWebSocketClient = new StandardWebSocketClient();
List<Transport> transports = new ArrayList<>(1);
transports.add(new WebSocketTransport(simpleWebSocketClient));

SockJsClient sockJsClient = new SockJsClient(transports);
sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec());

StompMessageHandler messageHandler = new StompMessageHandler();
StompWebSocketHandler websocketHandler = new StompWebSocketHandler(messageHandler, new StringMessageConverter());

WebSocketConnectionManager manager = new WebSocketConnectionManager(sockJsClient, websocketHandler, "ws://localhost:8080/stomp");

manager.start();

System.in.read();

我知道我可以通过使用@Configuration@Bean的注释来简化这一过程,但我正在努力做一个“原始”实现,这样我就能理解一切是如何协同工作的。< / p>

更多信息:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-client-api</artifactId>
    <version>1.1</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-websocket</artifactId>
    <version>8.0.0-RC10</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>

1 个答案:

答案 0 :(得分:4)

如果有趣的话,Spring Integration为WebSocketClient提供了一个实现。

是的,内部使用ConnectionManagerSupport

以下是test-case,演示了如何从@Configuration配置它。

但我认为您应该尝试开箱即用的WebSocketHandler实施 - SubProtocolWebSocketHandlerStompSubProtocolHandler