前端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();
        }
    }
}
相关推荐
程序员的世界你不懂7 分钟前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
索迪迈科技9 分钟前
网络请求库——Axios库深度解析
前端·网络·vue.js·北京百思可瑞教育·百思可瑞教育
gnip17 分钟前
JavaScript二叉树相关概念
前端
attitude.x1 小时前
PyTorch 动态图的灵活性与实用技巧
前端·人工智能·深度学习
β添砖java1 小时前
CSS3核心技术
前端·css·css3
空山新雨(大队长)1 小时前
HTML第八课:HTML4和HTML5的区别
前端·html·html5
猫头虎-前端技术2 小时前
浏览器兼容性问题全解:CSS 前缀、Grid/Flex 布局兼容方案与跨浏览器调试技巧
前端·css·node.js·bootstrap·ecmascript·css3·媒体
阿珊和她的猫2 小时前
探索 CSS 过渡:打造流畅网页交互体验
前端·css
元亓亓亓2 小时前
JavaWeb--day1--HTML&CSS
前端·css·html