• 如何在 Spring Boot 中使用 WebSocket


    在Spring Boot中使用WebSocket构建实时应用

    WebSocket是一种用于实现双向通信的网络协议,它非常适合构建实时应用程序,如在线聊天、实时通知和多人协作工具。Spring Boot提供了对WebSocket的支持,使得在应用程序中集成WebSocket变得非常容易。本文将介绍如何在Spring Boot中使用WebSocket构建实时应用。

    在这里插入图片描述

    什么是WebSocket?

    WebSocket是一种在单个TCP连接上实现全双工通信的协议。与HTTP不同,WebSocket允许服务器和客户端之间进行双向通信,而无需进行轮询或长轮询。这使得WebSocket非常适合构建实时应用,因为它能够实时推送数据,而无需等待客户端的请求。

    步骤1: 创建Spring Boot项目

    首先,您需要创建一个新的Spring Boot项目。您可以使用Spring Initializr(https://start.spring.io/)来生成一个基本的Spring Boot项目。

    确保在项目依赖中包含以下组件:

    • Spring Web
    • Spring WebSocket

    点击"Generate"按钮生成项目并下载。将项目导入到您的集成开发环境中。

    步骤2: 创建WebSocket端点

    WebSocket通信需要一个WebSocket端点,它将处理来自客户端的WebSocket连接。在Spring Boot中,您可以通过创建一个Java类并使用@ServerEndpoint注解来创建WebSocket端点。

    import org.springframework.stereotype.Component;
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArrayList;
    import java.util.concurrent.atomic.AtomicInteger;
    
    @ServerEndpoint("/websocket")
    @Component
    public class WebSocketServer {
        // 记录在线连接数
        private static AtomicInteger onlineCount = new AtomicInteger(0);
    
        // 存储每个客户端的WebSocket连接
        private static CopyOnWriteArrayList<WebSocketServer> webSocketSet = new CopyOnWriteArrayList<>();
    
        // 与客户端的WebSocket连接会话
        private Session session;
    
        @OnOpen
        public void onOpen(Session session) {
            this.session = session;
            webSocketSet.add(this); // 将WebSocket连接加入到集合中
            addOnlineCount(); // 在线连接数加1
            System.out.println("有新连接加入!当前在线人数为:" + getOnlineCount());
        }
    
        @OnClose
        public void onClose() {
            webSocketSet.remove(this); // 从集合中移除WebSocket连接
            subOnlineCount(); // 在线连接数减1
            System.out.println("有一连接关闭!当前在线人数为:" + getOnlineCount());
        }
    
        @OnMessage
        public void onMessage(String message, Session session) {
            System.out.println("来自客户端的消息:" + message);
    
            // 群发消息
            for (WebSocketServer item : webSocketSet) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        @OnError
        public void onError(Session session, Throwable error) {
            System.out.println("发生错误");
            error.printStackTrace();
        }
    
        public void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount.get();
        }
    
        public static synchronized void addOnlineCount() {
            onlineCount.incrementAndGet();
        }
    
        public static synchronized void subOnlineCount() {
            onlineCount.decrementAndGet();
        }
    }
    
    • 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
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70

    在上述示例中,我们创建了一个WebSocket端点WebSocketServer,它监听路径/websocket。该类使用了@ServerEndpoint注解,并包含了一些WebSocket事件的处理方法,如onOpenonCloseonMessageonError

    步骤3: 创建WebSocket客户端

    为了测试WebSocket端点,我们需要创建一个WebSocket客户端。您可以使用HTML和JavaScript创建一个简单的WebSocket客户端。

    DOCTYPE html>
    <html>
    <head>
        <title>WebSocket Exampletitle>
    head>
    <body>
        <h1>WebSocket Exampleh1>
        <div>
            <input type="text" id="message" placeholder="Enter a message">
            <button onclick="sendMessage()">Sendbutton>
        div>
        <ul id="messages">ul>
    
        <script>
            var socket = new WebSocket("ws://localhost:8080/websocket");
    
            socket.onmessage = function(event) {
                var messages = document.getElementById("messages");
                var message = document.createElement("li");
                message.appendChild(document.createTextNode(event.data));
                messages.appendChild(message);
            };
    
            function sendMessage() {
                var messageInput = document.getElementById("message");
                var message = messageInput.value;
                socket.send(message);
                messageInput.value = "";
            }
        script>
    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

    上述HTML页面创建了一个输入框和一个按钮,允许用户输入消息并将其发送到WebSocket服务器。当服务器发送消息时,它会将消息追加到页面上的消息列表中。

    步骤4: 运行应用程序

    现在您已经创建了WebSocket端点和客户端,可以启动Spring Boot应用程序并访问WebSocket客户端页面。您可以使用不同的浏览器窗口或标签页打开多个客户端,并尝试发送消息。您将看到消息实时传递给所有客户端,实现了实时通信。

    总结

    WebSocket是构建实时应用程序的强大工具,Spring Boot提供了对WebSocket的支持,使得在Spring Boot应用程序中集成WebSocket变得非常容易。在本文中,我们创建了一个简单的Spring Boot应用程序,包括WebSocket端点和WebSocket客户端,以演示如何使用WebSocket构建实时应用。希望本文对您有所帮助,让您更好地了解如何在Spring Boot中使用WebSocket。 Happy coding!

  • 相关阅读:
    [ Linux ] 动静态库 手把手教你写一个自己的库
    神经网络中的数值特征Embedding化方法
    实现数组去重的其中三种方法
    leetcode 46. 全排列
    前端 JS 经典:Class 面向对象
    在jupyter中更改、增加内核
    建木v2.6.0发布
    海康工业相机连续存图、录像功能介绍
    ansible安装及快速应用
    【AI绘画】免费GPU Tesla A100 32G算力部署Stable Diffusion
  • 原文地址:https://blog.csdn.net/stormjun/article/details/133746395