前端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();
        }
    }
}
相关推荐
AC赳赳老秦几秒前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen7 分钟前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
S1998_1997111609•X20 分钟前
论mysql国盾shell-sfa犯罪行为集团下的分项工程及反向注入原理尐深度纳米算法下的鐌檵鄐鉎行为
网络·数据库·网络协议·百度·开闭原则
千寻girling38 分钟前
《 Git 详细教程 》
前端·后端·面试
之歆2 小时前
DAY08_CSS浮动与行内块布局实战指南(下)
前端·css
yqcoder2 小时前
CSS Position 全解析:5 种定位模式详解
前端·css
Rhi6373 小时前
从零搭建项目:React 19 + Vite 8 + Tailwind CSS v4 实战配置
前端
竹林8183 小时前
用Viem替代ethers.js:从一次签名失败到完整迁移的实战记录
前端·javascript
之歆3 小时前
DAY08_CSS浮动与行内块布局实战指南(上)
前端·css
light blue bird3 小时前
主子端台二分法任务汇总组件
前端·数据库·.net·桌面端winform