I'm trying send websocket notification to specific endpoint. I created the following configuration
#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("/my-address");
registry.addEndpoint("/my-address").withSockJS();
}
}
I'm able to connect using postman on address ws://localhost:8080/my-address (session is established). Next I want to send notification to this endpoint within the same application (I'll be generating some messages internally). I use class SimpMessageSendingOperations:
simpMessageSendingOperations.convertAndSend("/my-address", exampleMessage);
None error message is generated and notification does not appear for websocket clients. I also tried
simpMessageSendingOperations.convertAndSend("/topic/my-address", exampleMessage);
and also
simpMessageSendingOperations.convertAndSend("/app/my-address", exampleMessage);
I don't know what I'm doing wrong. Can you help me with this issue?
Thanks in advance for help
Related
I've got a spring boot app in which I'm adding the websocket feature so that websocket client can make subscription request to subscribe messages off the websocket topic.
In my controller's method, I've added an annotation #SubscribeMapping("/topic/mytopic").
My WebSocketConfig looks like this:
#Configuration
#ComponentScan
#EnableWebSocket
public class WebSocketConfig extends WebSocketMessageBrokerConfiguratioSupport{
#Override
public void registerStompEndpoints(StompEndpointRegistry registry){
registry.addEndpoint("/my-app")
.setAllowedOrigin("*")
.withSockJS();
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry){
registry.enableSimpleBroker("/topic/");
registry.setApplicationDestinationPrefixes("/");
}
}
When I go to the browser and type:
http://localhost:<MY_PORT>/my-app
Then I get a response "Welcome to SockJS!". This indicates that Websocket server is indeed up and running.
But to my surprise, when I'm using my Postman's Websocket feature and trying to do a websocket subscription using the url:
ws://localhost:<MY_PORT>/my-app/topic/mytopic
This error is logged in the console: Invalid SockJS path /topic/mytopic - required to have 3 path segments
and the connection gets disconnected automatically.
Am I doing something wrong here? Please advise.
I have a spring boot application. I am trying to add the websocket piece to it. The problem is my angular client can't connect to it. I used smart websocket client google plugin, but still not able to connect. Here is the setup.
I am using Intellij Idea on localhost. the spring boot application is running on localhost:8080. I can see the WebSocketSession is runnign from intellij idea console.
Here is the setup:
#Slf4j
#RestController
public class WebsocketController {
#MessageMapping("/ws-on/hello")
#SendTo("/ws-on/greetings")
public UserStateIndicator greeting(UserStateIndicator indicator) throws Exception {
Thread.sleep(1000); // simulated delay
log.debug("websocket " + indicator.toString());
return indicator;
}
}
#Configuration
#EnableWebSocketMessageBroker
public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/ws-on");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws-on")
.setAllowedOrigins("http://localhost:4200")
.withSockJS();
}
}
my angular is running on localhost:4200.
I used ws://localhost:8080/ws-on as the url from StompJS to connect.
My question is how do I find the websocket url to connect, and how do I know the websocket is running on the spring boot server?
finally I figured it out. Because I am using SockJS on both angular and spring boot, so, the URL is actaully http not ws. the correct url to connect is then http://localost:8080/ws-on
After signing-in, the websockets cannot find the current user by session.getPrincipal() (it returns null).
Here is the Java code for WebSockets:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue", "/topic");
config.setApplicationDestinationPrefixes("/socket");
config.setUserDestinationPrefix("/user");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/app").withSockJS();
}
}
It seems like a Spring Boot bug - I am using 1.3.8 RELEASE. After refreshing the page, it gets the logged-in user properly.
And here is the front-end (subscription)
ngstomp.subscribeTo('/user/queue/message')
.callback(function(response) {
console.log('Test');
})
.withBodyInJson()
.connect();
I tried this solution: https://www.javacodegeeks.com/2014/11/spring-boot-based-websocket-application-and-capturing-http-session-id.html
But it's not working.
Please help me!
Why you required to have session.getPricncipal(). Spring provides Principal object to be injected automatically in your controller as following.
#MessageMapping("/message")
public String processMessageFromClient(#Payload String message, Principal principal) throws Exception {
messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/reply", name);
return name;
}
Reference: Spring Boot Websocket Example
My problem is I need to connect different port or server!
websocket server(localhost:8080) client server(localhost:random)
(failed: Error during WebSocket handshake: Unexpected response code: 403)
why?? I'm tired...
I already tried same port and I can success!
I can connect client(localhost:8080) and websocekt(localhost:8080).
I want to use websocket using (server side: java sts, tomcat 8.0).
questions
1. websocket can connect only same server and port???!!!!(no! please!)
2. If I can... what's the problem :(? Do u have any example?
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/myHandler").setAllowedOrigins("*");
}
#Bean
public WebSocketHandler myHandler() {
return new MyHandler();
}
}
Sounds like this is related to CORS https://en.wikipedia.org/wiki/Cross-origin_resource_sharing.
I assume you are using spring websocket as you didn't mention.
You will need to disable same origin policy in your websocket config class as below example,
#Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
}
#Override
protected boolean sameOriginDisabled() {
//disable CSRF for websockets
return true;
}
In my Spring Boot application I'm trying to implement a notifications functionality based on WebSockets.
I have provided a following configuration:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/notifications").withSockJS();
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
}
}
and trying to use SimpMessagingTemplate in order to send a message from server side to a specific client(user).
#Autowired
private SimpMessagingTemplate simpMessagingTemplate;
public void sendMessages() {
simpMessagingTemplate.convertAndSendToUser(%user%, "/horray", "Hello, World!");
}
Right now I don't understand a few things:
What value should be used for %user% parameter of
simpMessagingTemplate.convertAndSendToUser method ?
What is the correlation between my /notifications endpoint
registered in WebSocketConfig.registerStompEndpoints method and
destination parameter of
simpMessagingTemplate.convertAndSendToUser method and how to properly use it?
How to protect the users from reading other people's messages on the
client ?
The user parameter is the name that the client use when he subscribes the destination, see Spring Reference Chapter 26.4.11 User Destinations
Destination vs Endpoint:
Endpoint is the url where the websocket/message brocker is listening
Destination is the topic or subject within the message brocker