Skip to content

Commit a7f1c90

Browse files
feat: broadcast and expect multiple acks
Tests will be added in the parent repository. Related: - socketio/socket.io#1811 - socketio/socket.io#4163
1 parent 75455fa commit a7f1c90

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

lib/index.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export interface BroadcastFlags {
99
local?: boolean;
1010
broadcast?: boolean;
1111
binary?: boolean;
12+
timeout?: number;
1213
}
1314

1415
export interface BroadcastOptions {
@@ -42,6 +43,15 @@ export class Adapter extends EventEmitter {
4243
*/
4344
public close(): Promise<void> | void {}
4445

46+
/**
47+
* Returns the number of Socket.IO servers in the cluster
48+
*
49+
* @public
50+
*/
51+
public serverCount(): Promise<number> {
52+
return Promise.resolve(1);
53+
}
54+
4555
/**
4656
* Adds a socket to a list of room.
4757
*
@@ -140,6 +150,54 @@ export class Adapter extends EventEmitter {
140150
});
141151
}
142152

153+
/**
154+
* Broadcasts a packet and expects multiple acknowledgements.
155+
*
156+
* Options:
157+
* - `flags` {Object} flags for this packet
158+
* - `except` {Array} sids that should be excluded
159+
* - `rooms` {Array} list of rooms to broadcast to
160+
*
161+
* @param {Object} packet the packet object
162+
* @param {Object} opts the options
163+
* @param clientCountCallback - the number of clients that received the packet
164+
* @param ack - the callback that will be called for each client response
165+
*
166+
* @public
167+
*/
168+
public broadcastWithAck(
169+
packet: any,
170+
opts: BroadcastOptions,
171+
clientCountCallback: (clientCount: number) => void,
172+
ack: (...args: any[]) => void
173+
) {
174+
const flags = opts.flags || {};
175+
const packetOpts = {
176+
preEncoded: true,
177+
volatile: flags.volatile,
178+
compress: flags.compress
179+
};
180+
181+
packet.nsp = this.nsp.name;
182+
// we can use the same id for each packet, since the _ids counter is common (no duplicate)
183+
packet.id = this.nsp._ids++;
184+
185+
const encodedPackets = this.encoder.encode(packet);
186+
187+
let clientCount = 0;
188+
189+
this.apply(opts, socket => {
190+
// track the total number of acknowledgements that are expected
191+
clientCount++;
192+
// call the ack callback for each client response
193+
socket.acks.set(packet.id, ack);
194+
195+
socket.client.writeToEngine(encodedPackets, packetOpts);
196+
});
197+
198+
clientCountCallback(clientCount);
199+
}
200+
143201
/**
144202
* Gets a list of sockets by sid.
145203
*

0 commit comments

Comments
 (0)