2018-07-06 11:20:35 -04:00
|
|
|
// Copyright 2018 Ryan Dahl <ry@tinyclouds.org>
|
|
|
|
// All rights reserved. MIT License.
|
|
|
|
import { typedArrayToArrayBuffer } from "./util";
|
2018-07-06 11:27:36 -04:00
|
|
|
import { deno as fbs } from "./msg_generated";
|
2018-07-06 11:20:35 -04:00
|
|
|
|
|
|
|
export type MessageCallback = (msg: Uint8Array) => void;
|
|
|
|
//type MessageStructCallback = (msg: pb.IMsg) => void;
|
|
|
|
|
|
|
|
const channels = new Map<string, MessageCallback[]>();
|
|
|
|
|
|
|
|
export function sub(channel: string, cb: MessageCallback): void {
|
|
|
|
let subscribers = channels.get(channel);
|
|
|
|
if (!subscribers) {
|
|
|
|
subscribers = [];
|
|
|
|
channels.set(channel, subscribers);
|
|
|
|
}
|
|
|
|
subscribers.push(cb);
|
|
|
|
}
|
|
|
|
|
2018-07-06 11:27:36 -04:00
|
|
|
deno.recv((channel: string, ab: ArrayBuffer) => {
|
|
|
|
const subscribers = channels.get(channel);
|
2018-07-06 11:20:35 -04:00
|
|
|
if (subscribers == null) {
|
2018-07-06 11:27:36 -04:00
|
|
|
throw Error(`No subscribers for channel "${channel}".`);
|
2018-07-06 11:20:35 -04:00
|
|
|
}
|
|
|
|
|
2018-07-06 11:27:36 -04:00
|
|
|
const ui8 = new Uint8Array(ab);
|
2018-07-06 11:20:35 -04:00
|
|
|
for (const subscriber of subscribers) {
|
2018-07-06 11:27:36 -04:00
|
|
|
subscriber(ui8);
|
2018-07-06 11:20:35 -04:00
|
|
|
}
|
|
|
|
});
|