Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { channel, Sender, Receiver } from '../channel/index'
- import { Barrier } from '../async/index'
- import { Hub, Address, Forward, Protocol } from './hub'
- export class NetworkHub implements Hub {
- private readonly sender: Sender<[Address, any]>
- private readonly receiver: Receiver<[Address, any]>
- private readonly barrier: Barrier
- private readonly socket: WebSocket
- private configuration?: RTCConfiguration
- private address?: Address
- constructor(private readonly endpoint: string) {
- const [sender, receiver] = channel<[Address, any]>()
- this.sender = sender
- this.receiver = receiver
- this.barrier = new Barrier()
- this.socket = new WebSocket(this.endpoint)
- this.socket.addEventListener('message', event => this.on_message(event))
- this.socket.addEventListener('error', event => this.on_error(event))
- this.socket.addEventListener('close', () => this.on_close())
- }
- /** Returns this hubs network binding information */
- public binding(): Promise<[Address, RTCConfiguration]> {
- return this.barrier.run(() => [this.address!, this.configuration!])
- }
- /** Sends a message to a peer on the network. */
- public send<T>(to: Address, data: T): Promise<void> {
- return this.barrier.run(() => {
- const type = 'forward'
- const from = this.address!
- const forward = { type, from, to, data } as Forward
- this.socket.send(JSON.stringify(forward) )
- })
- }
- /** Receives a message from a peer on the network. */
- public async receive(): Promise<[Address, any]> {
- const { value } = await this.receiver.next()
- return value as [Address, any]
- }
- private on_message(event: MessageEvent) {
- const protocol = JSON.parse(event.data) as Protocol
- switch(protocol.type) {
- case 'binding': {
- const { address, configuration } = protocol
- this.configuration = configuration
- this.address = address
- this.barrier.resume()
- break
- }
- case 'forward': {
- const { from, data } = protocol
- this.sender.send([from, data])
- break
- }
- }
- }
- private on_error(error: Event) {
- this.sender.end()
- throw error
- }
- private on_close() {
- this.sender.end()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement