前端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();
        }
    }
}
相关推荐
万少5 小时前
小龙虾(openclaw),轻松玩转自动发帖
前端·人工智能·后端
Jagger_6 小时前
抱怨到躺床关灯的一次 DIY 记录
前端
陈随易9 小时前
前端大咖mizchi不满Rust、TypeScript却爱上MoonBit
前端·后端·程序员
whinc11 小时前
🚀 两年小程序开发,我把踩过的坑做成了开源 Skills
前端·微信小程序·ai编程
sure28212 小时前
React Native中创建自定义渐变色
前端·react native
KKKK12 小时前
SSE(Server-Sent Events)流式传输原理和XStream实践
前端·javascript
子兮曰13 小时前
Humanizer-zh 实战:把 AI 初稿改成“能发布”的技术文章
前端·javascript·后端
Din13 小时前
主动取消的防抖
前端·javascript·typescript
百度地图汽车版13 小时前
【AI地图 Tech说】第九期:让智能体拥有记忆——打造千人千面的小度想想
前端·后端
臣妾没空13 小时前
Elpis 全栈框架:从构建到发布的完整实践总结
前端·后端