Nanfeng

Notes on software development, code, and curious ideas

Implementing a Broadcast Message Queue in Cocos Creator

Design

  1. Maintain a persistent client-server connection for broadcast messages.
  2. Append received messages to a queue.
  3. Periodically remove one message from the queue.
  4. Put the message in a Label, clone its node, animate it from right to left, and destroy the clone when the animation ends.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const messageQueue: string[] = [];

ws.addEventListener('message', event => {
const data = String(event.data);
console.log('Received data:', data);
messageQueue.push(data);
});

this.schedule(() => {
const data = messageQueue.shift();
if (typeof data === 'undefined') return;

this._view._TextC_broadcast.string = data;
const broadcastNode = instantiate(this._view._TextC_broadcast.node);
broadcastNode.parent = this._view._TextC_broadcast.node.parent;

tween(broadcastNode)
.to(broadcastTime * 1.5, { position: new Vec3(x, 0, 0) })
.call(() => broadcastNode.destroy())
.start();
}, 1);

Using the component scheduler preserves the component’s this context and makes the callback easier to stop when the component is disabled or destroyed. For high message volume, define queue limits and decide whether to drop, combine, or prioritize old messages.

+