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

websocket-react使用

问题

在一个应用中,如果需要在不同的组件之间共享同一个WebSocket连接,可以采用多种方法来实现。
比如:单例模式、全局变量、react context

React上下文(React Context)

如果你使用的是React,可以使用React Context来共享WebSocket连接。通过创建一个WebSocket上下文,可以在整个应用中提供和消费这个WebSocket连接。

// WebSocketContext.js
import React, { createContext, useContext, useEffect, useState } from 'react';const WebSocketContext = createContext(null);export const WebSocketProvider = ({ children }) => {const [socket, setSocket] = useState(null);useEffect(() => {const ws = new WebSocket('ws://example.com/socket');setSocket(ws);return () => {ws.close();};}, []);return (<WebSocketContext.Provider value={socket}>{children}</WebSocketContext.Provider>);
};export const useWebSocket = () => {return useContext(WebSocketContext);
};// Component1.js
import React from 'react';
import { useWebSocket } from './WebSocketContext';const Component1 = () => {const socket = useWebSocket();useEffect(() => {if (socket) {socket.addEventListener('message', handleMessage);}return () => {if (socket) {socket.removeEventListener('message', handleMessage);}};}, [socket]);const handleMessage = (event) => {console.log('Message in Component 1:', event.data);};return <div>Component 1</div>;
};export default Component1;// Component2.js
import React from 'react';
import { useWebSocket } from './WebSocketContext';const Component2 = () => {const socket = useWebSocket();useEffect(() => {if (socket) {socket.addEventListener('message', handleMessage);}return () => {if (socket) {socket.removeEventListener('message', handleMessage);}};}, [socket]);const handleMessage = (event) => {console.log('Message in Component 2:', event.data);};return <div>Component 2</div>;
};export default Component2;// App.js
import React from 'react';
import { WebSocketProvider } from './WebSocketContext';
import Component1 from './Component1';
import Component2 from './Component2';const App = () => {return (<WebSocketProvider><Component1 /><Component2 /></WebSocketProvider>);
};export default App;

实例

WebSocketContext.ts

// contexts/WebSocketContext.tsimport React from 'react';
import WebSocketService from '../services/WebSocketService';// 此处允许值为 null
const WebSocketContext = React.createContext<WebSocketService | null>(null);export default WebSocketContext;

WebSocketService.ts

import { GetServerVersionResponse } from '@renderer/ipc/renderer_to_main_ipc_invoker/proxy/fpp'type CallbackFunction = (message: any) => void;
type InvokeDevIpFilesResponse = {path: stringfolder: boolean}class WebSocketService {public static instance: WebSocketService;public ws: WebSocket;public listeners: Record<string, CallbackFunction[]>;public constructor(url: string) {this.ws = new WebSocket(url);this.listeners = {};// 设置WebSocket事件监听器  this.ws.onmessage = this.handleMessage.bind(this);this.ws.onopen = this.handleOpen.bind(this);this.ws.onerror = this.handleError.bind(this);this.ws.onclose = this.handleClose.bind(this);}public static getInstance(url?: string): WebSocketService {if (!WebSocketService.instance) {if (!url) {throw new Error("WebSocketService instance has not been created yet. Please provide a URL.");}WebSocketService.instance = new WebSocketService(url);}return WebSocketService.instance;}public sendCommand(command: object): void {if (this.ws.readyState === WebSocket.OPEN) {this.ws.send(JSON.stringify(command));} else {console.error('WebSocket is not open.');}}public subscribe(command: string, callback: CallbackFunction): void {if (!this.listeners[command]) {this.listeners[command] = [];}this.listeners[command].push(callback);}public unsubscribe(command: string, callback: CallbackFunction): void {if (this.listeners[command]) {const index = this.listeners[command].indexOf(callback);if (index !== -1) {this.listeners[command].splice(index, 1);}}}//接收消息并处理private handleMessage(event: MessageEvent): void {const message = JSON.parse(event.data);console.log(message)if ( message.version ) {this.triggerCallbacks('version', message);} else if(Array.isArray(message)){const bagsList = message.filter(item => item.path && item.path.endsWith('.bag')) .map(item => item.path); if(bagsList){this.triggerCallbacks('bags', message);}}// 其他消息类型 在这里添加类似的处理逻辑}private triggerCallbacks(eventType: string, message: any): void {if (this.listeners[eventType]) {this.listeners[eventType].forEach((callback) => {callback(message);});}}private handleOpen(): void {console.log('WebSocket connected.');}private handleError(error: Event): void {console.error('❓ WebSocket error:', error);}private handleClose(): void {console.log('❌ WebSocket disconnected.');}public close(): void {this.ws.close();}public getGuiVersion(): Promise<string> {return new Promise((resolve, reject) => {const handleVersionMessage = (message: any) => {if (message.version) {resolve(message.version);this.unsubscribe('version', handleVersionMessage);}};this.subscribe('version', handleVersionMessage);this.sendCommand({ command: 'version' });setTimeout(() => {reject(new Error('Timeout waiting for GUI version.'));this.unsubscribe('version', handleVersionMessage);}, 5000);});}public getBagsList(): Promise<InvokeDevIpFilesResponse[]> {return new Promise((resolve, reject) => {const handleBagsMessage = (message: any) => {console.log(message)resolve(message);this.unsubscribe('bags', handleBagsMessage);};this.subscribe('bags', handleBagsMessage);const command = {command: 'bags',pattern: '*'};this.sendCommand(command);setTimeout(() => {reject(new Error('Timeout waiting for bags list.'));this.unsubscribe('bags', handleBagsMessage);}, 5000);});}public getMvizLink(): Promise<GetServerVersionResponse> {return new Promise((resolve, reject) => {const handleBagsMessage = (message: any) => {console.log(message)resolve(message);this.unsubscribe('bags', handleBagsMessage);};this.subscribe('bags', handleBagsMessage);const command = {command: 'bags',pattern: '*'};this.sendCommand(command);setTimeout(() => {reject(new Error('Timeout waiting for bags list.'));this.unsubscribe('bags', handleBagsMessage);}, 5000);});}}export default WebSocketService;

App.js

// App.js 或其他顶层组件import React from 'react';
import WebSocketContext from './contexts/WebSocketContext';
import WebSocketService from './services/WebSocketService';function App() {// 创建 WebSocketService 实例, 可以在这里传递你需要连接的WebSocket服务器的URLconst webSocketInstance = WebSocketService.getInstance('ws://your-websocket-url');return (// 使用 WebSocketContext.Provider 包裹你的组件并传递 value<WebSocketContext.Provider value={webSocketInstance}>{/* 这里是其他组件 */}</WebSocketContext.Provider>);
}export default App;

// SomeComponent.jsx

// SomeComponent.jsximport React, { useContext } from 'react';
import WebSocketContext from './contexts/WebSocketContext';function SomeComponent() {// 使用 useContext 钩子获取 WebSocketService 实例const webSocket = useContext(WebSocketContext);// 接下来可以使用 webSocket 发送消息或订阅事件// ...return (// 组件的其余部分);
}export default SomeComponent;

(占个坑,后续更新一下)

相关文章:

websocket-react使用

问题 在一个应用中&#xff0c;如果需要在不同的组件之间共享同一个WebSocket连接&#xff0c;可以采用多种方法来实现。 比如&#xff1a;单例模式、全局变量、react context React上下文&#xff08;React Context&#xff09; 如果你使用的是React&#xff0c;可以使用Re…...

【总结】nginx源码编译安装报错./configure: error: SSL modules require the OpenSSL library.

问题现象 源码编译安装nginx时&#xff0c;执行./configure …… --with-http_ssl_module 命令安装https模块&#xff0c;需要用到openssl&#xff0c;由于机器缺少openssl库&#xff0c;报如下错误。 …… checking for openat(), fstatat() ... found checking for getaddr…...

昇思25天学习打卡营第15天|两个分类实验

打卡 目录 打卡 实验1&#xff1a;K近邻算法实现红酒聚类 数据准备 模型构建--计算距离 计算演示 模型预测 实验2&#xff1a;基于MobileNetv2的垃圾分类 任务说明 数据集 参数配置&#xff08;训练/验证/推理&#xff09; 数据预处理 MobileNetV2模型搭建 Mobile…...

实践:Redis6.0配置文件解读

详细解读redis配置文件 https://raw.githubusercontent.com/redis/redis/6.2/redis.conf Units 配置数据单位换算关系配置大小单位&#xff1a;当需要内存大小时&#xff0c;可以指定。开头定义了一些基本的度量单位&#xff0c;只支持bytes&#xff0c;不支持bit&#xff0…...

【Go系列】Go语言的网络服务

承上启下 我们既然知道了Go语言的语法&#xff0c;也了解到了Go语言如何协同工作机制。那么对于这样一款天生支持高并发的语言&#xff0c;它的用武之地自然而然的就是网络服务了。我们今天学学如何使用网络服务。 开始学习 Go语言使用网络服务 在Go语言中&#xff0c;使用网…...

CS110L(Rust)

1.Rust 语法总结 数值类型 有符号整数: i8, i16, i32, i64无符号整数: u8, u16, u32, u64 变量声明 声明变量: let i 0; // 类型推断let n: i32 1; // 显式类型声明 可变变量: let mut n 0; n n 1; 字符串 注意&#xff0c;let s: str "Hello world";…...

免费恢复软件有哪些?电脑免费使用的 5 大数据恢复软件

您是否在发现需要的文件时不小心删除了回收站中的文件&#xff1f;您一定对误操作感到后悔。文件永远消失了吗&#xff1f;还有机会找回它们吗&#xff1f;当然有&#xff01;您可以查看这篇文章&#xff0c;挑选 5 款功能强大的免费数据恢复软件&#xff0c;用于 Windows 和 M…...

Flink History Server配置

目录 问题复现 History Server配置 HADOOP_CLASSPATH配置 History Server配置 问题修复 启动flink集群 启动Histroty Server 问题复现 在bigdata111上执行如下命令开启socket&#xff1a; nc -lk 9999 如图&#xff1a; 在bigdata111上执行如下命令运行flink应用程序 …...

ASPICE过程改进原则:确保汽车软件开发的卓越性能

"在汽车行业中&#xff0c;软件已经成为驱动创新和增强产品功能的核心要素。然而&#xff0c;随着软件复杂性的增加&#xff0c;确保软件质量、可靠性和性能成为了一项严峻的挑战。ASPICE标准的引入&#xff0c;为汽车软件开发提供了一套全面的过程改进框架&#xff0c;以…...

HDU1005——Number Sequence,HDU1006——Tick and Tick,HDU1007——Quoit Design

目录 HDU1005——Number Sequence 题目描述 超时代码 代码思路 正确代码 代码思路 HDU1006——Tick and Tick 题目描述 运行代码 代码思路 HDU1007——Quoit Design 题目描述 运行代码 代码思路 HDU1005——Number Sequence 题目描述 Problem - 1005 超时代码…...

uniapp form表单校验

公司的一个老项目&#xff0c;又要重新上架&#xff0c;uniapp一套代码&#xff0c;打包生成iOS端发布到App Store&#xff0c;安卓端发布到腾讯应用宝、OPPO、小米、华为、vivo&#xff0c;安卓各大应用市场上架要求不一样&#xff0c;可真麻烦啊 光一个表单校验&#xff0c;…...

构建RSS订阅机器人:观察者模式的实践与创新

在信息爆炸的时代&#xff0c;如何高效地获取和处理信息成为了一个重要的问题。RSS订阅机器人作为一种自动化工具&#xff0c;能够帮助我们从海量信息中筛选出我们感兴趣的内容。 一、RSS 是什么&#xff1f;观察者模式又是什么&#xff1f; RSS订阅机器人是一种能够自动订阅…...

芯片基础 | `wire`类型引发的学习

在Verilog中&#xff0c;wire类型是一种用于连接模块内部或模块之间的信号的数据类型。wire类型用于表示硬件中的物理连线&#xff0c;它可以传输任何类型的值&#xff08;如0、1、高阻态z等&#xff09;&#xff0c;但它在任何给定的时间点上只能有一个确定的值。 wire类型通…...

如何在AWS上构建Apache DolphinScheduler

引言 随着云计算技术的发展&#xff0c;Amazon Web Services (AWS) 作为一个开放的平台&#xff0c;一直在帮助开发者更好的在云上构建和使用开源软件&#xff0c;同时也与开源社区紧密合作&#xff0c;推动开源项目的发展。 本文主要探讨2024年值得关注的一些开源软件及其在…...

Quartus II 13.1添加新的FPGA器件库

最近需要用到Altera的一款MAX II 系列EPM240的FPGA芯片&#xff0c;所以需要给我的Quartus II 13.1添加新的器件库&#xff0c;在此记录一下过程。 1 下载所需的期间库 进入Inter官网&#xff0c;&#xff08;Altera已经被Inter收购&#xff09;https://www.intel.cn/content…...

【html】html的基础知识(面试重点)

一、如何理解HTML语义化 1、思考 A、在没有任何样式的前提下&#xff0c;将代码在浏览器打开&#xff0c;也能够结构清晰的展示出来。标题是标题、段落是段落、列表是列表。 B、便于搜索引擎优化。 2、参考答案 A、让人更容易读懂&#xff08;增加代码可读性&#xff09;。 B、…...

Java 网络编程(TCP编程 和 UDP编程)

1. Java 网络编程&#xff08;TCP编程 和 UDP编程&#xff09; 文章目录 1. Java 网络编程&#xff08;TCP编程 和 UDP编程&#xff09;2. 网络编程的概念3. IP 地址3.1 IP地址相关的&#xff1a;域名与DNS 4. 端口号&#xff08;port&#xff09;5. 通信协议5.1 通信协议相关的…...

STM32 | 看门狗+RTC源码解析

点击上方"蓝字"关注我们 作业 1、使用基本定时7,完成一个定时喂狗的程序 01、上节回顾 STM32 | 独立看门狗+RTC时间(第八天)02、定时器头文件 #ifndef __TIM_H#define __TIM_H​#include "stm32f4xx.h"​void Tim3_Init(void);void Tim7_Init(void);​…...

filebeat,kafka,clickhouse,ClickVisual搭建轻量级日志平台

springboot集成链路追踪 springboot版本 <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.3</version><relativePath/> <!-- lookup parent from…...

Django实战项目之进销存数据分析报表——第一天:Anaconda 环境搭建

引言 Anaconda是一个流行的Python和R语言的发行版&#xff0c;它包含了大量预安装的数据科学、机器学习库和科学计算工具。使用Anaconda可以轻松地创建隔离的环境&#xff0c;每个环境都可以有自己的一套库和Python版本&#xff0c;非常适合多项目开发。本文将指导你如何安装A…...

华为OD机试-食堂供餐-二分法

import java.util.Arrays; import java.util.Scanner;public class DemoTest3 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint a in.nextIn…...

Python爬虫(一):爬虫伪装

一、网站防爬机制概述 在当今互联网环境中&#xff0c;具有一定规模或盈利性质的网站几乎都实施了各种防爬措施。这些措施主要分为两大类&#xff1a; 身份验证机制&#xff1a;直接将未经授权的爬虫阻挡在外反爬技术体系&#xff1a;通过各种技术手段增加爬虫获取数据的难度…...

微服务商城-商品微服务

数据表 CREATE TABLE product (id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 商品id,cateid smallint(6) UNSIGNED NOT NULL DEFAULT 0 COMMENT 类别Id,name varchar(100) NOT NULL DEFAULT COMMENT 商品名称,subtitle varchar(200) NOT NULL DEFAULT COMMENT 商…...

鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/

使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题&#xff1a;docker pull 失败 网络不同&#xff0c;需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...

vulnyx Blogger writeup

信息收集 arp-scan nmap 获取userFlag 上web看看 一个默认的页面&#xff0c;gobuster扫一下目录 可以看到扫出的目录中得到了一个有价值的目录/wordpress&#xff0c;说明目标所使用的cms是wordpress&#xff0c;访问http://192.168.43.213/wordpress/然后查看源码能看到 这…...

莫兰迪高级灰总结计划简约商务通用PPT模版

莫兰迪高级灰总结计划简约商务通用PPT模版&#xff0c;莫兰迪调色板清新简约工作汇报PPT模版&#xff0c;莫兰迪时尚风极简设计PPT模版&#xff0c;大学生毕业论文答辩PPT模版&#xff0c;莫兰迪配色总结计划简约商务通用PPT模版&#xff0c;莫兰迪商务汇报PPT模版&#xff0c;…...

【Veristand】Veristand环境安装教程-Linux RT / Windows

首先声明&#xff0c;此教程是针对Simulink编译模型并导入Veristand中编写的&#xff0c;同时需要注意的是老用户编译可能用的是Veristand Model Framework&#xff0c;那个是历史版本&#xff0c;且NI不会再维护&#xff0c;新版本编译支持为VeriStand Model Generation Suppo…...

Vue 3 + WebSocket 实战:公司通知实时推送功能详解

&#x1f4e2; Vue 3 WebSocket 实战&#xff1a;公司通知实时推送功能详解 &#x1f4cc; 收藏 点赞 关注&#xff0c;项目中要用到推送功能时就不怕找不到了&#xff01; 实时通知是企业系统中常见的功能&#xff0c;比如&#xff1a;管理员发布通知后&#xff0c;所有用户…...

TCP/IP 网络编程 | 服务端 客户端的封装

设计模式 文章目录 设计模式一、socket.h 接口&#xff08;interface&#xff09;二、socket.cpp 实现&#xff08;implementation&#xff09;三、server.cpp 使用封装&#xff08;main 函数&#xff09;四、client.cpp 使用封装&#xff08;main 函数&#xff09;五、退出方法…...

WEB3全栈开发——面试专业技能点P4数据库

一、mysql2 原生驱动及其连接机制 概念介绍 mysql2 是 Node.js 环境中广泛使用的 MySQL 客户端库&#xff0c;基于 mysql 库改进而来&#xff0c;具有更好的性能、Promise 支持、流式查询、二进制数据处理能力等。 主要特点&#xff1a; 支持 Promise / async-await&#xf…...