I am trying to create a simple chat application using websockets. I followed this tutorial: https://www.baeldung.com/websockets-spring.
This is my config:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat");
registry.addEndpoint("/chat").withSockJS();
}
}
@Controller
public class WebSocketController {
@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
return new OutputMessage(message.getFrom(), message.getText(), Instant.now());
}
}
@Builder
@Getter
public class Message {
private final String from;
private final String text;
}
@Builder
@Getter
public class OutputMessage {
private final String from;
private final String text;
private final Instant date;
}
At the start of the application I got:
2021-12-31 14:22:39.442 INFO 1952 --- [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
I thought I had everything configured so I decided to try to connect using postman, but without success :/ I executed the following endpoints:
ws://localhost/app/chat
ws://localhost:8080/app/chat
ws://localhost/chat
ws://localhost:8080/chat
none of them work :/
I am using Postman Websockets beta to perform requests.
Did I miss something in the configuration or am I using postaman wrong?
According to the reply from Postman Team in their blog: https://blog.postman.com/postman-supports-websocket-apis/ . Postman does not support subscribe to a topic at present. So in this case, you can only connect to server with 'ws://localhost:8080/chat', but you can not send messages between web client and server. What a pity!
- registry.addEndpoint("/chat").withSockJS();
+ registry.addEndpoint("/chat");
It works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With