当前位置: 首页 > news >正文

前端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();}}
}

http://www.lryc.cn/news/433357.html

相关文章:

  • 读取realsense d455双目及imu
  • 浮点的运算
  • 对随机游走问题的分析特定行为模式的建模
  • JVM面试(七)G1垃圾收集器剖析
  • php转职golang第一期
  • java后端服务监控与告警:Prometheus与Grafana集成
  • 【系统架构设计师】工厂方法设计模式
  • 怎样解决OpenEuler下载sdl2失败
  • 基于Python的自然语言处理系列(2):Word2Vec(负采样)
  • 每日一题|牛客竞赛|四舍五入|字符串+贪心+模拟
  • 大数据之Flink(六)
  • 设计模式学习[5]---装饰模式
  • 3.C_数据结构_栈
  • Debian11安装DolphinScheduler
  • C语言深度剖析--不定期更新的第五弹
  • python之事务
  • 文件加密软件都有哪些?推荐6款文件加密工具
  • Docker中的容器内部无法使用vi命令怎么办?
  • 【Linux系统编程】TCP实现--socket
  • 企业微信hook协议接口,聚合群聊客户管理工具开发
  • Selenium集成Sikuli基于图像识别的自动化测试
  • 【STM32实物】基于STM32设计的智能仓储管理系统(程序代码电路原理图实物图讲解视频设计文档等)——文末资料下载
  • libtool 中的 .la 文件说明
  • NLP-transformer学习:(6)dataset 加载与调用
  • 数据库系统 第43节 数据库复制
  • LabVIEW FIFO详解
  • 如何验证VMWare WorkStation的安装?
  • 论文阅读:AutoDIR Automatic All-in-One Image Restoration with Latent Diffusion
  • C++ | Leetcode C++题解之第392题判断子序列
  • 操作系统概述(三、虚拟化)