Class A can create the WebSocket connection and expose it through a shared service or, in a small browser project, through a global reference:
1 | const socket = new WebSocket('wss://your-socket-url'); |
Class B can obtain the same object and add another listener:
1 | const socket = (window as any).socket as WebSocket | undefined; |
Using addEventListener allows both classes to receive messages; assigning socket.onmessage again would replace the previous handler. For a larger project, a dedicated socket manager or event bus is cleaner and easier to type than storing the connection on window. Use wss:// in production and implement reconnection, authentication, and error handling as required.