Question

For a project I'm building in Spring I'd like to implement websocket. I have found a solution in the form of STOMP, but I can not find a way to send a websocket message to a single user, only a way to do a full broadcast to all clients. What are good alternatives that plug easily into Spring and that I can use to send and receive messages? I have a self-rolled user system in Spring (rather than using Spring Security) and I want to tie it in with that.

Edit: I'd like to point out that I want a solution that degrades gracefully to other protocols for communication, in the way that socket.io does this.

Was it helpful?

Solution

For using Spring with websockets, have a look at the new Spring Websocket support in Spring 4, this is a presentation about it.

According to the documentation, Spring supports connection a single user, as well as broadcast:

Spring Framework allows @Controller classes to have both HTTP request handling and WebSocket message handling methods. Furthermore, a Spring MVC request handling method, or any application method for that matter, can easily broadcast a message to all interested WebSocket clients or to a specific user.

This is an example of a broadcast, which you already can do:

@Controller
public class GreetingController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(3000); // simulated delay
        return new Greeting("Hello, " + message.getName() + "!");
    }

}

According to the documentation, the way to not do broadcast and reply only to the calling customer is to ommit the @SendTo annotation:

By default the return value from an @SubscribeMapping method is sent as a message directly back to the connected client and does not pass through the broker. This is useful for implementing request-reply message interactions;

OTHER TIPS

This should help

private final SimpMessageSendingOperations messagingTemplate;

List<String> messages = new ArrayList<>(Arrays.asList("Bar","Foo"));

@AutoWired
public YourConstructor(SimpMessageSendingOperations messagingTemplate){
       this.messagingTemplate = messagingTemplate;
}

@Scheduled(fixedDelay=1500)
public void sendMessages() {

for (String message : messages) {
   this.messagingTemplate.convertAndSendToUser(user, "/queue/messages", message);
        }
}

PS: @Scheduled Annotation for timed task

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top