Cocos Creator Shared WebSocket: Connection Service and Message Subscribers

Create a Shared WebSocket Connection

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
 2
 3
 4
 5
 6
 7
 8
 9
10
const socket = new WebSocket('wss://your-socket-url');
(window as any).socket = socket;

socket.addEventListener('open', () => {
  console.log('WebSocket connection established');
});

socket.addEventListener('message', event => {
  console.log('Class A received WebSocket data', event.data);
});

Class B can obtain the same object and add another listener:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const socket = (window as any).socket as WebSocket | undefined;

if (socket) {
  const handleMessage = (event: MessageEvent) => {
    console.log('Class B received WebSocket data', event.data);
  };

  socket.addEventListener('message', handleMessage);

  // Later, when Class B is destroyed:
  // socket.removeEventListener('message', handleMessage);
}

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.