在Spring Boot中实现基于WebSocket的实时通信

大家好,我是微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!

WebSocket简介与概念

WebSocket是一种在单个TCP连接上进行全双工通信的协议,它允许客户端和服务器之间进行实时数据传输。在Web应用程序中,特别是需要实时更新的场景(如聊天应用、实时数据展示等),WebSocket提供了一种高效的解决方案。

1. Spring Boot中使用WebSocket

Spring Boot对WebSocket提供了良好的支持,通过Spring WebSocket模块可以轻松地实现WebSocket通信。

package cn.juwatech.websocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic"); // 启用简单消息代理,消息前缀为/topic
        config.setApplicationDestinationPrefixes("/app"); // 设置应用程序目标前缀
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket-example") // 定义WebSocket端点
                .setAllowedOrigins("*") // 允许跨域访问
                .withSockJS(); // 支持SockJS协议
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

2. 编写WebSocket控制器

package cn.juwatech.websocket;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class WebSocketController {

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public WebSocketMessageModel sendMessage(WebSocketMessageModel message) {
        return message;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

3. 前端实现WebSocket通信

在前端使用JavaScript和SockJS库实现WebSocket通信:

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script>
        var stompClient = null;

        function connect() {
            var socket = new SockJS('/websocket-example');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/messages', function (response) {
                    showMessage(JSON.parse(response.body));
                });
            });
        }

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

        function sendMessage() {
            var message = document.getElementById('message').value;
            stompClient.send("/app/chat", {}, JSON.stringify({ 'content': message }));
        }

        function showMessage(message) {
            var messageArea = document.getElementById('messages');
            var messageElement = document.createElement('li');
            messageElement.textContent = message.content;
            messageArea.appendChild(messageElement);
        }
    </script>
</head>
<body>
    <div>
        <button onclick="connect()">Connect</button>
        <button onclick="disconnect()">Disconnect</button>
    </div>
    <div>
        <input type="text" id="message" placeholder="Enter message">
        <button onclick="sendMessage()">Send</button>
    </div>
    <ul id="messages"></ul>
</body>
</html>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.

结论

通过本文的介绍,我们深入理解了如何在Spring Boot项目中实现基于WebSocket的实时通信。WebSocket提供了一种高效的方式来处理实时通信需求,结合Spring Boot的支持,我们可以轻松地集成和管理WebSocket。