Java websocket在SpringBoot中使用

Java websocket在SpringBoot中使用

导入坐标

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>3.2.3</version>
</dependency>

配置websocket

  • 新建config包,取名WebSocketConfiguration,并加入@Configuration注解。
java 复制代码
/**
 * WebSocket配置类,用于注册WebSocket的Bean
 */
@Configuration
public class WebSocketConfiguration {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

设置接受和发送路径

使用注解@ServerEndpoint("/bunnyWs/{sid}")填入前端的路径。里面有几个不同方法。

  1. 连接建立成功@OnOpen
  2. 关闭连接@OnClose
  3. 发送消息@OnMessage
  4. 发送消息
java 复制代码
@Component
@ServerEndpoint("/bunnyWs/{sid}")
public class WebSocketServer {
    private static final Map<String, Session> sessionsMap = new HashMap<>();

    // 连接建立成功
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端:" + sid + "建立连接");
        sessionsMap.put(sid, session);
    }

    // 关闭连接
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionsMap.remove(sid);
    }

    // 收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("收到来自客户端:" + sid + "的信息:" + message);
    }
    
    // 发送消息
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionsMap.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

调用定时任务发送

使用定时任务测试

java 复制代码
@Component
public class WebSocketTask {
    @Autowired
    WebSocketServer webSocketServer;

    @Scheduled(cron = "0/1 * * * * ?")
    public void setWebSocketServer() {
        webSocketServer.sendToAllClient("这是来自服务端的消息:" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
    }
}

前端模板

html 复制代码
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
</head>
<body>
    <input id="text" type="text" />
    <button onclick="send()">发送消息</button>
    <button onclick="closeWebSocket()">关闭连接</button>
    <div id="message">
    </div>
</body>
<script type="text/javascript">
    var websocket = null;
    var clientId = Math.random().toString(36).substr(2);

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        //连接WebSocket节点
        websocket = new WebSocket("ws://localhost:8080/bunnyWs/"+clientId);
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(){
        setMessageInnerHTML("连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    
    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }
</script>
</html>
tById('text').value;
        websocket.send(message);
    }
    
    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }
</script>
</html>
相关推荐
苏小瀚20 小时前
算法---位运算
java·算法
Camel卡蒙20 小时前
数据结构——二叉搜索树Binary Search Tree(介绍、Java实现增删查改、中序遍历等)
java·开发语言·数据结构
2401_8414956420 小时前
【数据结构】基于Floyd算法的最短路径求解
java·数据结构·c++·python·算法··floyd
珹洺21 小时前
Java-Spring入门指南(二十七)Android Studio 第一个项目搭建与手机页面模拟器运行
java·spring·android studio
程序猿DD21 小时前
Java 25 中的 6 个新特性解读
java·后端
稻草猫.21 小时前
文件 IO
java·笔记·后端·java-ee·idea
laopeng30121 小时前
基于Spring AI Deep Researcher Agent
java·人工智能·spring
子豪-中国机器人21 小时前
《C++ STL 基础入门》教案
java·开发语言
java_t_t1 天前
集合工具类
java·集合
消失的旧时光-19431 天前
ScheduledExecutorService
android·java·开发语言