Ijaz
Ijaz

Reputation: 117

Basic websocket with Spring without STOMP and SockJS

I have implemented the following websocket endpoint

@MessageMapping("/socket/{myId}/")
@SendTo("/queue/myqueue")
public MyObject getObject(@DestinationVariable String myId) throws Exception {

    return new MyObject("MyId:" + myId);
}

Now how can I send message to that endpoint from one of my service.java class? There will be front-end client as well, which will read the message from websocket once the service.java class's method send some message to websocket endpoint. I am a little confused that how can I do that?

Any help would be appreciated

Upvotes: 4

Views: 8127

Answers (2)

Dhiraj Ray
Dhiraj Ray

Reputation: 837

When using a raw websocket(without STOMP), the message sent lacks of information to make Spring route it to a specific message handler method (we don't have any messaging protocol), so instead of annotating your controller, you'll have to implement a WebSocketHandler by extending TextWebSocketHandler public void handleTextMessage(WebSocketSession session, TextMessage message){ }

Checkout an example here spring boot websocket without STOMP and SockJs

Upvotes: 4

Tolledo
Tolledo

Reputation: 609

You should take a look at SimpMessagingTemplate. For example, if you want to send a message for a specific user from your service class:

@Autowired
private SimpMessagingTemplate messagingTemplate;

public void sendMessage(User user, String message) {
    Objects.requireNonNull(user);
    Objects.requireNonNull(message);
    messagingTemplate.convertAndSendToUser(user.getUsername(), "/queue/myqueue", message);
}

Upvotes: 0

Related Questions