@SendTo annotation in Spring Boot

@SendTo annotation in Spring Boot

In Spring Boot, @SendToannotation is a very useful annotation, which can be used to realize the message forwarding function of WebSocket. This article will introduce @SendTothe principle, usage and sample code of annotations.

insert image description here

What is @SendTo annotation

@SendToAnnotations are annotations used in Spring Boot to send messages to specified destinations. It can be used in the message forwarding function in WebSocket to forward the message sent by the client to the specified destination, so that the specified client can receive the message.

The principle of @SendTo annotation

@SendToThe principle of annotation is to use the message subscription and publishing mechanism in WebSocket. In WebSocket, each client can subscribe to a specified destination, and when a message is published to the destination, all clients subscribed to the destination will receive the message.

@SendToAn annotation can send a message to a specified destination, so that the client subscribed to the destination can receive the message. When sending a message, @SendTothe annotation will encapsulate the message into an Messageobject and send it to the specified destination. The client can receive the message when it subscribes to the destination.

How to use the @SendTo annotation

Using @SendToannotations is very simple, just add the annotation to the method and specify the destination to be sent. Here is an @SendToexample using annotations:

@RestController
public class WebSocketController {
    
    

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

}

In the above code, @MessageMapping("/hello")the annotation indicates that this method is used to process the message sent by the client /hello. @SendTo("/topic/greetings")The annotation indicates that the returned message is sent to /topic/greetingsthe destination.

When the client subscribes to /topic/greetingsthe destination, it can receive the message. The sample code is as follows:

var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({
    
    }, function(frame) {
    
    
    stompClient.subscribe('/topic/greetings', function(greeting){
    
    
        showGreeting(JSON.parse(greeting.body).content);
    });
});

In the above code, stompClient.subscribe('/topic/greetings', function(greeting){...})it represents the subscription /topic/greetingsdestination, and triggers the callback function when a message is received, and displays the message on the page.

sample code

In order to better understand @SendTohow to use annotations, a complete sample code is given below. The sample code implements a simple chat room function, users can send messages in the chat room, and other users can receive the messages.

First, we need to create a WebSocket configuration class for configuring WebSocket related parameters. code show as below:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    
    

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

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

}

In the above code, configureMessageBrokerthe method is used to configure the message broker, and registerStompEndpointsthe method is used to register the WebSocket endpoint. enableSimpleBroker("/topic")Indicates that a simple message broker is enabled and messages are sent to /topicthe destination. setApplicationDestinationPrefixes("/app")Indicates that the setting application prefix is /app​​. addEndpoint("/chat").withSockJS()Indicates to register a WebSocket endpoint and enable SockJS support.

Next, we need to create a WebSocket controller class that will handle messages sent by the client. code show as below:

@RestController
public class WebSocketController {
    
    

    private final SimpMessagingTemplate messagingTemplate;

    public WebSocketController(SimpMessagingTemplate messagingTemplate) {
    
    
        this.messagingTemplate = messagingTemplate;
    }

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
    
    
        return chatMessage;
    }

    @MessageMapping("/chat.addUser")
    @SendTo("/topic/public")
    public ChatMessage addUser(@Payload ChatMessage chatMessage,
                               SimpMessageHeaderAccessor headerAccessor) {
    
    
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        return chatMessage;
    }

}

In the above code, @MessageMapping("/chat.sendMessage")the annotation indicates that this method is used to process the message sent by the client /chat.sendMessage. @SendTo("/topic/public")The annotation indicates that the returned message is sent to /topic/publicthe destination. sendMessagemethod for sending messages.

@MessageMapping("/chat.addUser")The annotation indicates that this method is used to process the message sent by the client /chat.addUser. addUsermethod for adding users.

Finally, we need to create a front-end page that displays the chat room interface and handles the messages entered by the user. code show as below:

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat Example</title>
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;

        function connect() {
      
      
            var socket = new SockJS('/chat');
            stompClient = Stomp.over(socket);
            stompClient.connect({
      
      }, function (frame) {
      
      
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/public', function (chatMessage) {
      
      
                    showMessage(JSON.parse(chatMessage.body));
                });
            });
        }

        function disconnect() {
      
      
            if (stompClient !== null) {
      
      
                stompClient.disconnect();
            }
            console.log("Disconnected");
        }

        function sendMessage() {
      
      
            var sender = $("#sender").val();
            var content = $("#content").val();
            stompClient.send("/app/chat.sendMessage", {
      
      }, JSON.stringify({
      
      
                sender: sender,
                content: content
            }));
        }

        function addUser() {
      
      
            var sender = $("#sender").val();
            stompClient.send("/app/chat.addUser", {
      
      }, JSON.stringify({
      
      
                sender: sender,
                content: ' has joined the chat'
            }));
        }

        function showMessage(message) {
      
      
            $("#chat").append("<tr><td>" + message.sender + ": " + message.content + "</td></tr>");
        }

        $(function () {
      
      
            $("form").on('submit', function (e) {
      
      
                e.preventDefault();
            });
            connect();
            $("#send").click(function () {
      
      
                sendMessage();
                $("#content").val("");
            });
            $("#join").click(function () {
      
      
                addUser();
                $("#sender").prop("readonly", true);
                $("#join").prop("disabled", true);
                $("#send").prop("disabled", false);
                $("#content").prop("disabled", false);
            });
        });
    </script>
</head>
<body>
<div>
    <form>
        <label for="sender">Username:</label>
        <input type="text" id="sender" name="sender"/>
        <button type="button" id="join">Join</button>
        <br/>
        <label for="content">Message:</label>
        <input type="text" id="content" name="content"/>
        <button type="button" id="send" disabled="disabled">Send</button>
    </form>
</div>
<div>
    <table id="chat"></table>
</div>
</body>
</html>

In the above code, connectthe method is used to establish a WebSocket connection. disconnectMethod is used to disconnect the WebSocket connection. sendMessagemethod for sending messages. addUsermethod for adding users. showMessagemethod for displaying messages.

Summarize

Through the introduction of this article, we understand @SendTothe principle and usage of annotations in Spring Boot. @SendToAnnotations are the key annotations to implement the WebSocket message forwarding function, which allows us to easily send and receive messages.

Guess you like

Origin blog.csdn.net/2301_77835649/article/details/131481657