SpringBoot使用WebSocket

SpringBoot使用WebSocket

mvn依赖

java 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

后端配置文件

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

WS服务

java 复制代码
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {

    private static final ConcurrentHashMap<String, Session> SESSION_MAP = new ConcurrentHashMap<>();

    private String userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.userId = userId;
        SESSION_MAP.put(userId, session);
        log.info("用户连接成功,userId={}, 当前在线人数={}", userId, SESSION_MAP.size());
    }

    @OnClose
    public void onClose() {
        if (userId != null) {
            SESSION_MAP.remove(userId);
            log.info("用户连接关闭,userId={}, 当前在线人数={}", userId, SESSION_MAP.size());
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到用户{}的消息:{}", userId, message);

        String response = "服务端已收到:" + message;

        try {
            session.getBasicRemote().sendText(response);
        } catch (IOException e) {
            log.error("发送消息失败,userId={}", userId, e);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket异常,userId={}", userId, error);
    }

    public static void sendMessageToAll(String message) {
        SESSION_MAP.forEach((uid, session) -> {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("广播消息失败,userId={}", uid, e);
            }
        });
    }

    public static void sendMessageToUser(String userId, String message) {
        Session session = SESSION_MAP.get(userId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("发送消息给指定用户失败,userId={}", userId, e);
            }
        }
    }
}

前端测试文件

javascript 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 测试</title>
</head>
<body>

<h3>WebSocket 测试</h3>

用户ID:<input id="userId" value="user1"/>
<button onclick="connect()">连接</button>
<button onclick="disconnect()">断开</button>

<br/><br/>

发送消息:<input id="message"/>
<button onclick="send()">发送</button>

<br/><br/>

<div>
    <strong>日志:</strong>
    <pre id="log"></pre>
</div>

<script>
    let ws;

    function log(text) {
        document.getElementById('log').innerText += text + '\n';
    }

    function connect() {
        const userId = document.getElementById('userId').value;
        ws = new WebSocket('ws://localhost:8080/ws/' + userId);

        ws.onopen = function () {
            log('连接成功');
        };

        ws.onmessage = function (event) {
            log('收到消息:' + event.data);
        };

        ws.onclose = function () {
            log('连接关闭');
        };

        ws.onerror = function (error) {
            log('连接异常');
            console.error(error);
        };
    }

    function disconnect() {
        if (ws) {
            ws.close();
        }
    }

    function send() {
        const message = document.getElementById('message').value;
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(message);
        } else {
            log('WebSocket 未连接');
        }
    }
</script>

</body>
</html>
相关推荐
JavaEdge.5 小时前
Redis 连接断开后的自动重连操作
spring boot·redis·后端·lettuce·tcp keepalive
EatFan14 小时前
Spring Boot 4 落地观察:从 yudao-cloud、matecloud、JPower 看国产脚手架的升级路线与迁移清单
java·spring boot·后端·spring cloud·微服务·后端开发·jdk 21
波力海苔夹心脆67515 小时前
C# 序列化与反序列化详解:System.Text.Json、Newtonsoft.Json、XmlSerializer 用法、特性选项与安全实践
经验分享·后端·c#·json·.net
JavaGuide16 小时前
NVIDIA 又开源了!这次给 AI Agent 加上权限管控
前端·后端
excel16 小时前
prisma 如何处理数据库竞态
前端·数据库·后端
hasty18 小时前
只监听本机为何仍需鉴权?Cline Hub 的 WebSocket 信任边界解析
网络·websocket·网络协议
IT_陈寒19 小时前
Java线程池这破玩意,差点让我周末加班排查到凌晨
前端·人工智能·后端
弈栈录19 小时前
Java AI 应用的异步化与高并发设计
java·后端·架构
凤山老林20 小时前
Spring Boot 集成 iText 7 实现动态 PDF 生成与电子签章:合同、报表场景实战
spring boot·后端·pdf·itext7·电子签章