typescript ChannelBuffer.ts

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript ChannelBuffer.ts相关的知识,希望对你有一定的参考价值。

import {Channel} from "eris";
import {injectable} from "inversify";
import ChannelBuffer from "./ChannelBuffer";

@injectable()
export default class MessageBuffer {
    private readonly _buffers: Array<ChannelBuffer<string>> = [];

    public AddItem(channel: Channel, message: string): void {
        if (!this._buffers[channel.id]) {
            this._buffers[channel.id] = new ChannelBuffer<string>(
                channel,
                async (channel, messages) => {
                    let builder: string = "";
                    for (let message of messages) {
                        if (builder.length + message.length > 2000) {
                            await channel.createMessage(builder);
                            builder = "";
                        }

                        builder += `${message}\n`;
                    }

                    await channel.createMessage(builder);
                },
            );
        }

        this._buffers[channel.id].addItem(message);
    }
};
import {Mutex} from "await-semaphore";
import {Channel} from "eris";
import {setInterval} from "timers";

const mutex: Mutex = new Mutex();

export default class ChannelBuffer<T> {
    private _messages: T[] = [];

    constructor(private _channel: Channel, tick: Function, interval: number = 1000) {
        setInterval(async () => {
            const release: any = await mutex.acquire();

            let messages: T[]     = this._messages.slice();
            this._messages.length = 0;

            release();

            if (messages.length === 0) {
                return;
            }

            tick(this._channel, messages);
        }, interval);
    }

    public addItem(obj: T): void {
        mutex.acquire().then((release) => {
            this._messages.push(obj);

            release();
        });
    }
};

以上是关于typescript ChannelBuffer.ts的主要内容,如果未能解决你的问题,请参考以下文章

NIO之ChannelBuffer

Netty详解之整体架构

Java NIO框架Netty教程 – Object对象传递

缩略muduo库:Buffer 缓冲区

缩略muduo库:Buffer 缓冲区

NIO学习笔记