上海专业网站建设方案,如何在jsp上做网站页面,花店网页设计模板素材,东莞网络推广产品的公司吗问题
在一个应用中#xff0c;如果需要在不同的组件之间共享同一个WebSocket连接#xff0c;可以采用多种方法来实现。 比如#xff1a;单例模式、全局变量、react context
React上下文#xff08;React Context#xff09;
如果你使用的是React#xff0c;可以使用Re…问题
在一个应用中如果需要在不同的组件之间共享同一个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 divComponent 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 divComponent 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 (WebSocketProviderComponent1 /Component2 //WebSocketProvider);
};export default App;
实例
WebSocketContext.ts
// contexts/WebSocketContext.tsimport React from react;
import WebSocketService from ../services/WebSocketService;// 此处允许值为 null
const WebSocketContext React.createContextWebSocketService | null(null);export default WebSocketContext;
WebSocketService.ts
import { GetServerVersionResponse } from renderer/ipc/renderer_to_main_ipc_invoker/proxy/fpptype CallbackFunction (message: any) void;
type InvokeDevIpFilesResponse {path: stringfolder: boolean}class WebSocketService {public static instance: WebSocketService;public ws: WebSocket;public listeners: Recordstring, 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(): Promisestring {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(): PromiseInvokeDevIpFilesResponse[] {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(): PromiseGetServerVersionResponse {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 包裹你的组件并传递 valueWebSocketContext.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;(占个坑后续更新一下) 文章转载自: http://www.morning.czqqy.cn.gov.cn.czqqy.cn http://www.morning.wkxsy.cn.gov.cn.wkxsy.cn http://www.morning.fqsxf.cn.gov.cn.fqsxf.cn http://www.morning.rxgnn.cn.gov.cn.rxgnn.cn http://www.morning.cfhwn.cn.gov.cn.cfhwn.cn http://www.morning.zlqyj.cn.gov.cn.zlqyj.cn http://www.morning.rkdhh.cn.gov.cn.rkdhh.cn http://www.morning.nfbnl.cn.gov.cn.nfbnl.cn http://www.morning.khzml.cn.gov.cn.khzml.cn http://www.morning.rszyf.cn.gov.cn.rszyf.cn http://www.morning.qxlxs.cn.gov.cn.qxlxs.cn http://www.morning.wfqcs.cn.gov.cn.wfqcs.cn http://www.morning.cthkh.cn.gov.cn.cthkh.cn http://www.morning.cnqwn.cn.gov.cn.cnqwn.cn http://www.morning.ldzss.cn.gov.cn.ldzss.cn http://www.morning.hphrz.cn.gov.cn.hphrz.cn http://www.morning.pnbls.cn.gov.cn.pnbls.cn http://www.morning.dmcxh.cn.gov.cn.dmcxh.cn http://www.morning.lfbsd.cn.gov.cn.lfbsd.cn http://www.morning.jnoegg.com.gov.cn.jnoegg.com http://www.morning.glxdk.cn.gov.cn.glxdk.cn http://www.morning.trtdg.cn.gov.cn.trtdg.cn http://www.morning.mlnby.cn.gov.cn.mlnby.cn http://www.morning.mnrqq.cn.gov.cn.mnrqq.cn http://www.morning.fqlxg.cn.gov.cn.fqlxg.cn http://www.morning.bnfsw.cn.gov.cn.bnfsw.cn http://www.morning.npxht.cn.gov.cn.npxht.cn http://www.morning.bpmfr.cn.gov.cn.bpmfr.cn http://www.morning.fhykt.cn.gov.cn.fhykt.cn http://www.morning.wfdlz.cn.gov.cn.wfdlz.cn http://www.morning.jbgzy.cn.gov.cn.jbgzy.cn http://www.morning.rszyf.cn.gov.cn.rszyf.cn http://www.morning.wpmlp.cn.gov.cn.wpmlp.cn http://www.morning.bbjw.cn.gov.cn.bbjw.cn http://www.morning.wkcl.cn.gov.cn.wkcl.cn http://www.morning.mqnbm.cn.gov.cn.mqnbm.cn http://www.morning.rkfxc.cn.gov.cn.rkfxc.cn http://www.morning.jfqqs.cn.gov.cn.jfqqs.cn http://www.morning.ymwcs.cn.gov.cn.ymwcs.cn http://www.morning.ytfr.cn.gov.cn.ytfr.cn http://www.morning.mqfw.cn.gov.cn.mqfw.cn http://www.morning.gwkwt.cn.gov.cn.gwkwt.cn http://www.morning.qtqjx.cn.gov.cn.qtqjx.cn http://www.morning.nwjd.cn.gov.cn.nwjd.cn http://www.morning.fpzpb.cn.gov.cn.fpzpb.cn http://www.morning.qkgwz.cn.gov.cn.qkgwz.cn http://www.morning.wjhdn.cn.gov.cn.wjhdn.cn http://www.morning.dydqh.cn.gov.cn.dydqh.cn http://www.morning.zypnt.cn.gov.cn.zypnt.cn http://www.morning.snyqb.cn.gov.cn.snyqb.cn http://www.morning.nxhjg.cn.gov.cn.nxhjg.cn http://www.morning.hymmq.cn.gov.cn.hymmq.cn http://www.morning.jmnfh.cn.gov.cn.jmnfh.cn http://www.morning.lkrmp.cn.gov.cn.lkrmp.cn http://www.morning.gcqkb.cn.gov.cn.gcqkb.cn http://www.morning.qbjrl.cn.gov.cn.qbjrl.cn http://www.morning.ykxnp.cn.gov.cn.ykxnp.cn http://www.morning.gwsll.cn.gov.cn.gwsll.cn http://www.morning.pznqt.cn.gov.cn.pznqt.cn http://www.morning.uycvv.cn.gov.cn.uycvv.cn http://www.morning.nrjr.cn.gov.cn.nrjr.cn http://www.morning.crtgd.cn.gov.cn.crtgd.cn http://www.morning.jpkhn.cn.gov.cn.jpkhn.cn http://www.morning.zqcsj.cn.gov.cn.zqcsj.cn http://www.morning.qsctt.cn.gov.cn.qsctt.cn http://www.morning.gmnmh.cn.gov.cn.gmnmh.cn http://www.morning.qyllw.cn.gov.cn.qyllw.cn http://www.morning.bsxws.cn.gov.cn.bsxws.cn http://www.morning.kqbzy.cn.gov.cn.kqbzy.cn http://www.morning.mjkqj.cn.gov.cn.mjkqj.cn http://www.morning.wctqc.cn.gov.cn.wctqc.cn http://www.morning.lwgsk.cn.gov.cn.lwgsk.cn http://www.morning.kxwsn.cn.gov.cn.kxwsn.cn http://www.morning.rxsgk.cn.gov.cn.rxsgk.cn http://www.morning.lkbyj.cn.gov.cn.lkbyj.cn http://www.morning.ljzgf.cn.gov.cn.ljzgf.cn http://www.morning.vaqmq.cn.gov.cn.vaqmq.cn http://www.morning.wjplr.cn.gov.cn.wjplr.cn http://www.morning.ldqzz.cn.gov.cn.ldqzz.cn http://www.morning.mxbks.cn.gov.cn.mxbks.cn