简体   繁体   中英

Writing a client to connect to websocket in spring boot

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.

I believe this is what you're 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 a similar server side 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 ad some othe configuration.

I believe you can figure out the rest ;)

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM