前端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();
        }
    }
}
相关推荐
枷锁—sha几秒前
【DVWA系列】——CSRF——Medium详细教程
android·服务器·前端·web安全·网络安全·csrf
枷锁—sha2 分钟前
跨站请求伪造漏洞(CSRF)详解
运维·服务器·前端·web安全·网络安全·csrf
guts°8 分钟前
10-ACL技术
网络·网络协议
群联云防护小杜18 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
汉得数字平台36 分钟前
【鲲苍提效】全面洞察用户体验,助力打造高性能前端应用
前端·前端监控
花海如潮淹42 分钟前
前端性能追踪工具:用户体验的毫秒战争
前端·笔记·ux
2301_780789665 小时前
UDP和TCP的主要区别是什么
服务器·网络协议·web安全·网络安全·udp
_丿丨丨_6 小时前
XSS(跨站脚本攻击)
前端·网络·xss
天天进步20156 小时前
前端安全指南:防御XSS与CSRF攻击
前端·安全·xss
拾光拾趣录8 小时前
括号生成算法
前端·算法