Writing a client to connect to websocket in spring boot
I believe this is what you're looking for
this is a similar server side code..
And here is the client side.. using org.springframework.web.socket.client.standard.StandardWebSocketClient ad some othe configuration.
I believe you can figure out the rest ;)
Cheers
FusionHS
Updated on June 14, 2022Comments
-
FusionHS almost 2 years
I'm trying to make a websocketed based server/client application using spring boot.
The server accepts a socket connection then when it recieves a text message from the client it will process it, then return some data. The server has a websocket handler that will correctly process a 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, is that I have no idea how to write a client that can connect to the server(assuming I wrote the server correctly) and by extensions how to send the message and how to receive that data on the client side.
I've failed to find an example of this, but there are plenty where a websocket is written that broadcasts to all clients subscribed to a socket, which I don't want.
The server uses the embeded tomcat server.