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>
相关推荐
曹牧22 分钟前
Java:“刷新雪崩”
java·开发语言
秋天的怀念_David24 分钟前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
千寻技术帮1 小时前
10454_基于Springboot的企业购销链管理系统
spring boot·mysql·vue·毕业设计·进销存
Forget the Dream2 小时前
Spring AI 2.0 系列(二):第一个 ChatClient——从注入到一次完整调用
java·人工智能·spring boot·ai·springai
张小姐的猫3 小时前
【基于 WebSocket 的多用户网页五子棋】—— 整合封装服务器模块设计实现2️⃣
服务器·websocket·网络协议
花椒技术4 小时前
花椒语音房联机五子棋:Go 服务端如何保证一回合只落一颗子
websocket·go
黑十4 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
神明不懂浪漫4 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
用户54817845909504 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
文丑颜不良啊4 小时前
LeetCode3341~3360题目解析
java·leetcode