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>
相关推荐
oliver_sys_log4 小时前
绕过 Yearning 查询体验限制:我做了一个 DataGrip 只读 SQL 代理
后端·mysql
水深火乐4 小时前
golang-jwt v5 入门
后端
carson9554 小时前
基于springboot和vue的文本文件上传下载在线编辑功能
后端
n8n5 小时前
Spring AI 提示词工程进阶:System / User / Assistant 角色、Prompt Template 动态拼装与多角色人设切换
后端
vipxieliang5 小时前
固定电话验证详解:区号、号码、分机号的完整验证
java·spring boot
步行cgn5 小时前
Spring Boot 主入口类上的 @Enable 和 @Scan 注解详解
java·spring boot·后端
Lyra_Infra5 小时前
云效主机部署场景下 Python 服务生命周期问题复盘
后端·python
程序员cxuan5 小时前
GPT images 2.5 一手实测,这也太颠了。。。
后端·程序员
xixingzhe25 小时前
SpringBoot DDD 实战入门文档
spring boot·spring·ddd
山岚的运维笔记6 小时前
mysql 专业笔记 -- 第 17 章:连接:连接三个具有相同名称 ID 的表
运维·数据库·笔记·后端·学习·mysql·dba