1
votes

I have this websocket server developed using Spring Boot. The server is working fine with a js based client.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").withSockJS();
        registry.addEndpoint("/chat");
    }

}

The controller:

@Controller
public class ChatController {

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public OutputMessage send(final Message message) throws Exception {

        final String time = new SimpleDateFormat("HH:mm").format(new Date());
        return new OutputMessage(message.getFrom(), message.getText(), time);
    }

}

This is the server side. Now, for the client, I have created a @ClientEndpoint and when I connect to the URI "ws://localhost:8080/spring-mvc-java/chat", I am able to establish a connection and I can see that the @OnOpen callback of @ClientEndpoint is triggered.

However, it seems that the userSession.getAsyncRemote().sendText(message) does not have any effect. I don't see the response from the server.

I can see the js client is:

  1. Connecting to the server var socket = new SockJS('/spring-mvc-java/chat')
  2. Subscribing stompClient.subscribe('/topic/messages',...
  3. Send the message stompClient.send("/app/chat",...

I am able to achieve the first step. How to achieve the 2nd and the 3rd step in a Java based client?

Thanks

1
when you say java based client, are you using any web socket library and stomp library? - Jos
No. No stomp, no sockjs. I am actually trying to follow this thing programmingforliving.com/2013/08/… - Yasin

1 Answers

0
votes

First of all you need a websocketclient and websocketstompclient

WebSocketClient client = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(client);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());

You have to custom handler from StompSessionHandler for

getPayloadType
handleFrame
afterConnected
handleException
handleTransportError

methods

StompSessionHandler sessionHandler = new CustomStompSessionHandler();

You can connect your sockets like this. You can accomplish sending and receiving messages

StompSession stompSession=stompClient.connect("ws://localhost:8080/chat",sessionHandler).get();

This two trigger your websocket topic/messages give you messages through the sockets

/app/chat sending Message to sockets

stompSession.subscribe("/topic/messages", sessionHandler);
stompSession.send("/app/chat", new Message("Hi", "user"));

do you want like this?