In an application, websockets generally exist in a singleton form, that is, websocket instances are always unique throughout the application. But sometimes when we want to use websocket instances, the websocket may not be instantiated yet, so we need to make it into an asynchronous form to obtain the instance.
1. Packaging. Create a file first
import EventEmitter from 'events'; // The events package is used hereconst ee = new EventEmitter(); class Ws { private wsUrl: string = ''; private socket: WebSocket | undefined; // socket instance private lockReconnect: boolean = false; // Re-chain private timeout: | undefined; // Initialize the socket, it is usually done once when the application starts, or you need to replace wsUrl public init(wsUrl: string) { = wsUrl; (); } // Get socket instance public getInstance(): Promise<WebSocket> { return new Promise((resolve, reject) => { if () { resolve(); } else { ('socket', (state: string) => { if (state === 'success') { resolve(); } else { reject(); } }); } }); } // Create socket private createWebSocket() { try { ('websocket start link'); const socket = new WebSocket(); ('close', () => { ('websocket link closed'); = undefined; (); }); ('error', () => { ('The websocket has an exception'); = undefined; (); }); ('open', () => { // Heartbeat detection can be performed here // (); ('websocket open'); = socket; ('socket', 'success'); }); ('message', (event) => { ('websocket received message', event); }); } catch (e) { ('socket catch error', e); (); } } // Reconnect private reconnect() { if () { return; } ('websocket is reconnecting'); = true; //If there is no connection, it will be reconnected all the time. Set delay to avoid too many requests && clearTimeout(); = setTimeout(() => { (); = false; }, 5000); } } export default new Ws();
2. Introduce and use
import socket from '@/utils/ws'; socket .getInstance() .then((ws) => { // The ws here is the instantiated websocket, you can directly use the websocket native API ('getInstance ws', ws); ('message', (event) => { ('ws received message', event); }); }) .catch(() => {});
The above is the detailed content of recording the process of websocket encapsulation. For more information about websocket encapsulation, please pay attention to my other related articles!