Home  >  Article  >  Java  >  How SpringBoot uses WebSocket to send group messages

How SpringBoot uses WebSocket to send group messages

WBOY
WBOYforward
2023-05-12 18:55:061504browse

WebSocket is a protocol for full-duplex communication over a single TCP connection that has been designated as a standard by the W3C. Using WebSocket makes data exchange between client and server much simpler. In the WebSocket protocol, the browser and the server only need to complete a handshake, and a persistent connection can be directly created between the two for bidirectional data transmission.

How SpringBoot uses WebSocket to send group messages

Features

  • When using WebSocket, you need to create a connection first, which makes Websocket a stateful protocol, part of the status information (such as identity authentication, etc.) can be omitted in the subsequent communication process.

  • WebSocket connections are created on port 80 (ws) or 443 (wss), the same port used by HTTP, so that basically all firewalls will not block WebSocket connections.

  • WebSocket uses the HTTP protocol for handshakes, so it can be naturally integrated into web browsers and HTTP servers at no additional cost.

  • Heartbeat messages (ping and pong) will be sent repeatedly to keep the WebSocket connection active.

  • Using this protocol, both the server and the client can know when a message starts or arrives.

  • WebSocket will send a special closing message when the connection is closed.

  • WebSocket supports cross-domain and can avoid Ajax limitations.

  • The HTTP specification requires browsers to limit the number of concurrent connections to two connections per host name, but when we use Websocket, this limit does not exist after the handshake is completed. , because the connection at this time is no longer an HTTP connection.

  • The WebSocket protocol supports extensions. Users can extend the protocol to implement some customized sub-protocols.

  • WebSocket has better binary support and better compression.

1. Add dependencies

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-websocket</artifactid>
</dependency>

2. Configure WebSocket

The Spring framework provides a WebSocket's STOMP support, STOMP is a simple interoperable protocol commonly used for asynchronous messaging between clients through an intermediary server.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 设置消息代理的前缀,如果消息的前缀为"/topic",就会将消息转发给消息代理(broker)
        // 再由消息代理广播给当前连接的客户端
        config.enableSimpleBroker("/topic");
        // 下面方法可以配置一个或多个前缀,通过这些前缀过滤出需要被注解方法处理的消息。
        // 例如这里表示前缀为"/app"的destination可以通过@MessageMapping注解的方法处理
        // 而其他 destination(例如"/topic""/queue")将被直接交给 broker 处理
        config.setApplicationDestinationPrefixes("/app");
    }
 
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 定义一个前缀为"/chart"的endpoint,并开启 sockjs 支持。
        // sockjs 可以解决浏览器对WebSocket的兼容性问题,客户端将通过这里配置的URL建立WebSocket连接
        registry.addEndpoint("/chat").withSockJS();
    }
}

3. Server code

According to the configuration of WebSocketConfig above, the @MessageMapping("/hello") annotated method will be used to receive "/app/hello" ” path, after processing the message in the annotation method, the message is forwarded to the path defined by @SendTo. The @SendTo path is a path prefixed with "/topic", so the message is handed over to the message broker, and then broadcasted by the broker.

@Controller
public class DemoController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Message greeting(Message message) throws Exception {
        return message;
    }

}
@Data
public class Message {

    private String name;
    
    private String content;

}

4. Front-end code

Create the chat.html page in the resources/static directory as the chat page.

nbsp;html>


    <meta>
    <title>群聊</title>
    <script></script>
    <script></script>
    <script></script>
    <script>
        var stompClient = null;

        // 根据是否已连接设置页面元素状态
        function setConnected(connected) {
            $("#connect").prop("disabled", connected);
            $("#disconnect").prop("disabled", !connected);
            if (connected) {
                $("#conversation").show();
                $("#chat").show();
            }
            else {
                $("#conversation").hide();
                $("#chat").hide();
            }
            $("#greetings").html("");
        }

        // 建立一个WebSocket连接
        function connect() {
            // 用户名不能为空
            if (!$("#name").val()) {
                return;
            }
            // 首先使用 SockJS 建立连接
            var socket = new SockJS(&#39;/chat&#39;);
            // 然后创建一个STOMP实例发起连接请求
            stompClient = Stomp.over(socket);
            // 连接成功回调
            stompClient.connect({}, function (frame) {
                // 进行页面设置
                setConnected(true);
                // 订阅服务端发送回来的消息
                stompClient.subscribe(&#39;/topic/greetings&#39;, function (greeting) {
                    // 将服务端发送回来的消息展示出来
                    showGreeting(JSON.parse(greeting.body));
                });
            });
        }

        // 断开WebSocket连接
        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            setConnected(false);
        }

        // 发送消息
        function sendName() {
            stompClient.send("/app/hello",
                {},
                JSON.stringify({&#39;name&#39;: $("#name").val(),&#39;content&#39;:$("#content").val()}));
        }

        // 将服务端发送回来的消息展示出来
        function showGreeting(message) {
            $("#greetings")
                .append("<div>" + message.name+":"+message.content + "");
        }

        // 页面加载后进行初始化动作
        $(function () {
            $( "#connect" ).click(function() { connect(); });
            $( "#disconnect" ).click(function() { disconnect(); });
            $( "#send" ).click(function() { sendName(); });
        });
    </script>


<div>
    <label>请输入用户名:</label>
    <input>
</div>
<div>
    <button>连接</button>
    <button>断开连接</button>
</div>
<div>
    <div>
        <label>请输入聊天内容:</label>
        <input>
    </div>
    <button>发送</button>
    <div>
        <div>群聊进行中...</div>
    </div>
</div>

  • SockJS is a browser JavaScript library that provides objects similar to WebSocket. SockJS provides you with a consistent, cross-browser Javascript API that creates a low-latency, full-duplex, cross-domain communication channel between the browser and the web server.

  • STOMP is Simple (or Streaming) Text Orientated Messaging Protocol. It provides an interoperable connection format that allows STOMP clients to communicate with any STOMP message broker (Broker) interacts.

  • @SendTo annotation, which forwards the message processed by the method to the broker, and then the broker broadcasts the message.

5. Verification results

Our request address: http://127.0.0.1:8086/chat.html

Login user: piao

How SpringBoot uses WebSocket to send group messages

Login user: admin

How SpringBoot uses WebSocket to send group messages

The above is the detailed content of How SpringBoot uses WebSocket to send group messages. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete