如何在 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端点。

java 复制代码
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();
    }
}

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

步骤3: 创建WebSocket客户端

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

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Example</title>
</head>
<body>
    <h1>WebSocket Example</h1>
    <div>
        <input type="text" id="message" placeholder="Enter a message">
        <button onclick="sendMessage()">Send</button>
    </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>

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

步骤4: 运行应用程序

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

总结

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

相关推荐
IT毕设梦工厂5 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
凡人的AI工具箱6 小时前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python
是店小二呀6 小时前
【C++】C++ STL探索:Priority Queue与仿函数的深入解析
开发语言·c++·后端
canonical_entropy6 小时前
金蝶云苍穹的Extension与Nop平台的Delta的区别
后端·低代码·架构
是梦终空6 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票
我叫啥都行7 小时前
计算机基础知识复习9.7
运维·服务器·网络·笔记·后端
工业互联网专业7 小时前
毕业设计选题:基于springboot+vue+uniapp的驾校报名小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码·课程设计
无名指的等待7128 小时前
SpringBoot中使用ElasticSearch
java·spring boot·后端
.生产的驴8 小时前
SpringBoot 消息队列RabbitMQ 消费者确认机制 失败重试机制
java·spring boot·分布式·后端·rabbitmq·java-rabbitmq
AskHarries9 小时前
Spring Boot利用dag加速Spring beans初始化
java·spring boot·后端