前端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();
        }
    }
}
相关推荐
许商2 分钟前
【stm32】【printf】
java·前端·stm32
JIngJaneIL11 分钟前
智慧物业|物业管理|基于SprinBoot+vue的智慧物业管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·论文·智慧物业管理系统
爬坑的小白14 分钟前
vue 2.0 路由跳转时新开tab
前端·javascript·vue.js
爬坑的小白14 分钟前
vue x 状态管理
前端·javascript·vue.js
凌览29 分钟前
一键去水印|5 款免费小红书解析工具推荐
前端·javascript·后端
lichong95133 分钟前
鸿蒙 web组件开发
前端·typescript
1024小神33 分钟前
在html中使用js动态交换两个元素的位置
前端
鹿鹿鹿鹿isNotDefined34 分钟前
逐步手写,实现符合 Promise A+ 规范的 Promise
前端·javascript·算法
一千柯橘34 分钟前
Electron - IPC 解决主进程和渲染进程之间的通信
前端
申阳35 分钟前
Day 16:02. 基于 Tauri 2.0 开发后台管理系统-项目初始化配置
前端·后端·程序员