前端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();
        }
    }
}
相关推荐
南囝coding6 分钟前
这个 361K Star 的项目,一定要收藏!
前端·后端·github
我不吃饼干6 分钟前
我给掘金写了一个给用户加标签的功能
前端·javascript·cursor
羚羊角uou25 分钟前
【C++】模拟实现map和set
java·前端·c++
90后的晨仔1 小时前
ArkTS 与 Swift 闭包的对比分析
前端·harmonyos
小小小小宇1 小时前
前端用户行为监控
前端
步行cgn1 小时前
Vue 事件修饰符详解
前端·javascript·vue.js
vvilkim1 小时前
Flutter 状态管理基础:深入理解 setState 和 InheritedWidget
前端·javascript·flutter
Magnum Lehar1 小时前
wpf3d游戏引擎前端ControlTemplate实现
前端·游戏引擎·wpf
早该学学了2 小时前
el-tabs问题解决大总结
前端
星河丶2 小时前
useEffect的清理函数的执行时机
前端·react.js