前端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();
        }
    }
}
相关推荐
GISer_Jing19 小时前
LangChain浏览器Agent开发全攻略
前端·ai·langchain
小李子呢021119 小时前
前端八股---脚手架工具Vue CLI(Webpack) vs Vite
前端·vue.js·webpack
2401_8858850419 小时前
群发彩信接口怎么开发?企业级彩信发送说明
前端·python
Freak嵌入式19 小时前
aiohttps异步HTTPS库:uPyPI+MicroPython一键安装
人工智能·python·网络协议·http·https·micropython
发光小北19 小时前
EtherCAT 转 Modbus TCP 网关如何应用?
网络协议·tcp/ip
PILIPALAPENG19 小时前
第2周 Day 5:前端转型AI开发,朋友问我,你到底在折腾啥?
前端·人工智能·python
Mintopia19 小时前
前端卡顿的真相:不是你代码慢,是你阻塞了
前端
kyriewen19 小时前
可选链 `?.`——再也不用写一长串 `&&` 了!
前端·javascript·ecmascript 6
Mintopia19 小时前
别再乱加缓存:一套判断"该不该缓存"的方法
前端
Leisureconfused19 小时前
【记录】Node版本兼容性问题及解决
前端·vue.js·npm·node.js