Writing a client to connect to websocket in spring for download

I am trying to create a websocket based server / client application using spring boot.

The server accepts a socket connection, then when it receives a text message from the client, it will process it and then return some data. There is a websocket handler on the server that will correctly process the request.

public class DataWebSocketHandler extends TextWebSocketHandler { private static Logger logger = LoggerFactory.getLogger(DataWebSocketHandler.class); private final DataService dataService; @Autowired public DataWebSocketHandler(DataService dataService) { this.dataService = dataService; } @Override public void afterConnectionEstablished(WebSocketSession session) { logger.debug("Opened new session in instance " + this); } @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { byte[] payload = this.dataService.getDataBytes(message.getPayload()); session.sendMessage(new BinaryMessage(payload)); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } } 

and registered

 @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(dataWebSocketHandler(), "/data").withSockJS(); } 

My problem is that I have no idea how to write a client that can connect to the server (provided that I wrote the server correctly) and extensions, how to send a message and how to get this data on the client side.

I could not find an example of this, but there are many places where websocket is written, which is broadcast to all clients subscribed to the socket, which I do not want.

The server uses the integrated tomcat server.

+5
source share
1 answer

I believe that this is what you are looking for

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo

this is similar server code.

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests. java

And here is the client side. Using org.springframework.web.socket.client.standard.StandardWebSocketClient, create some configuration.

I believe you can figure out the rest;)

Greetings

+3
source

Source: https://habr.com/ru/post/1216591/


All Articles