前端WebSocket客户端实现

复制代码
// 创建WebSocket连接
var socket = new WebSocket('ws://your-spring-boot-server-url/websocket-endpoint');

// 连接打开时触发
socket.addEventListener('open', function (event) {
    socket.send(JSON.stringify({type: 'JOIN', room: 'general'}));
});

// 监听从服务器来的消息
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

// 连接关闭时触发
socket.addEventListener('close', function (event) {
    console.log('Socket is closed. Reconnect will be attempted in 1 second.', event);
});

Vue.js示例

如果你的应用是基于Vue.js的,你可以直接在Vue组件中使用WebSocket,或者考虑使用如vue-socket.io这样的插件来简化开发过程。下面是一个基本的Vue组件中集成WebSocket的例子:

复制代码
export default {
    data() {
        return {
            socket: null
        }
    },
    mounted() {
        this.socket = new WebSocket('ws://your-spring-boot-server-url/websocket-endpoint');
        this.socket.onopen = (event) => {
            console.log('WebSocket connection opened!', event);
            this.socket.send(JSON.stringify({action: 'subscribe', topic: 'news'}));
        };
        this.socket.onmessage = (event) => {
            console.log('Received message:', event.data);
        };
        this.socket.onclose = (event) => {
            console.log('WebSocket connection closed.', event);
        };
    },
    beforeDestroy() {
        if (this.socket) {
            this.socket.close();
        }
    }
}
相关推荐
卸任19 小时前
Vibe coding工具使用心得
前端·ai编程
brien919 小时前
为什么模型标称 1M,Google Antigravity 聊到 256K 却突然失忆?我们给它做了个原生行内监控圆环
前端
修炼的dance20 小时前
录屏关键帧间隔多少合适?六档实测,2秒到10秒小了75.6%
前端
Lank_M20 小时前
关键帧从1秒拉到10秒,录屏小87.3%,摄像头小10.8%
前端
补码缩写20 小时前
用 ffprobe 拆录屏,八成字节在 29 个关键帧上
前端
百思不得小李20 小时前
一个复杂的动态表单是如何实现的
前端·设计模式
陈随易20 小时前
Cmder 停更 17 个月,2.0 支持 Windows Terminal
前端·后端·程序员
风骏时光牛马20 小时前
前沿视界
前端
kyriewen20 小时前
我扫了 814 个依赖,97 个还敢要 Node 10
前端·javascript·程序员
陈随易21 小时前
3000 万人在用的翻译插件,重写一遍就是一门生意
前端·后端·程序员