I am working on a Spring WebSocket Stomp Client for my WebSocket Server and I am getting conflicting information.
I have found 2 ways to get it to work and without going into too much detail I was wondering which way is considered the "correct" way of implementing the client.
Could somebody help me understand what the WebSocketConnectionManager is for?
Also, one more question, how do I keep the websocket connection open and the program running to accept new messages without having to write the line System.in.read().
1'st way: Using the SockJsClient directly
URI uri = new URI("ws://localhost:8080/stomp");
StandardWebSocketClient simpleWebSocketClient = new StandardWebSocketClient();
List 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();
2'nd way: Using the WebSocketConnectionManager
StandardWebSocketClient simpleWebSocketClient = new StandardWebSocketClient();
List 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();
I know that I could make this a lot simpler by using the Annotations for @Configuration and @Bean but I am trying to do a "raw" implementation so I can understand how everything works together.
A little more information:
org.springframework
spring-websocket
4.1.4.RELEASE
org.springframework
spring-messaging
4.1.4.RELEASE
javax.websocket
javax.websocket-client-api
1.1
org.apache.tomcat
tomcat-websocket
8.0.0-RC10
com.fasterxml.jackson.core
jackson-databind
2.5.0
解决方案
If it is interesting Spring Integration provides an implementation for the WebSocketClient.
And yes, internally it uses ConnectionManagerSupport.
Here is a test-case which demonstrate how to configure it from @Configuration.
But I think you should try with out-of-the-box WebSocketHandler implementation - SubProtocolWebSocketHandler, and StompSubProtocolHandler.