前端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();
        }
    }
}
相关推荐
SomeOtherTime5 分钟前
Geojson相关(AI回答)
java·前端·python
就叫_这个吧1 小时前
HTML常用标签及举例使用
前端·html
utf8mb4安全女神1 小时前
【rsyslog服务】把所有服务的“临界点”以上的错误都保存在/var/log/alert.log⽇志中
java·前端·javascript
YANQ6621 小时前
7.bundlesdf本地安装
前端·webpack·node.js
星夜夏空992 小时前
FreeRTOS学习(7)——任务列表
java·前端·学习
weixin_471383032 小时前
由浅入深递归练习
前端·javascript·vue.js
tedcloud1232 小时前
ai-engineering-from-scratch部署教程:从零搭建AI应用环境
服务器·前端·人工智能·系统架构·edge
Kurisu5752 小时前
全面战争:战锤3修改器下载2026最新
前端
丷丩3 小时前
MapLibre GL JS第21课:绘制GeoJSON点图标、注记
前端·javascript·gis·mapbox·maplibre gl js
LCG元3 小时前
现代Web应用高可用架构设计与性能调优实战
前端·wpf