nodejs仿照WebSocket实现QuickSocket实时通讯框架

一、QuickSocket协议部分

1、标志位:QS,长度16位
2、帧类型:1~255,长度8位,目前定义三种类型,可扩展

0 -> 保留,不可用
1 -> MSG 消息类型
2 -> PING 主动心跳包
3 -> PONG 返回心跳包

3、数据长度:0 ~ 65535,长度16位

如果超过最大长度会丢弃超出部分数据

4、校验码:0 ~ 255, 长度8位,校验协议头部数据

校验码计算方式:头部所有字节取异或

5、数据:长度 0 ~ 65535字节

QuickSocket协议

代码 https://github.com/sxyudi/QuickSocket

二、实现部分
1、QsServer端,建立socket监听服务器,处理事件信息

QsServer.prototype.listen = function(options, customer) {

    options = options || {};
    options.host = options.host || '127.0.0.1';
    options.port = options.port || 80;

    const that = this;
    this.server = net.createServer(function(socket) { 
        console.log("client comming", socket.remoteAddress, socket.remotePort);
        const client = new QsClient(socket);
        client.uid = this.uid++;
        client.ts = Math.floor(Date.now() / 1000);
        that.clients.push(client);
        that.onConnect(client, customer);
    });

    this.server.on("listening", function() {
        console.log("start listening...", options.host, options.port);
        that.onListening(customer);
    });

    this.server.on("error", function(err) {
        console.log("listen error");
        that.onError(err, customer);
    });

    this.server.on("close", function() {
        console.log("server stop listener");
        that.onClose(customer);
    });

    this.server.listen({
        port: options.port,
        host: options.host,
        exclusive: true,
    });
};

2、QsClient端,建立socket链接,处理事件信息

// 处理接受数据
QsClient.prototype.onData = function(data) {

    // 上一次剩余没有处理完的半包;
    if (this.last_pkg) {
        this.last_pkg = Buffer.concat([this.last_pkg, data], this.last_pkg.length + data.length);
    } else {
        this.last_pkg = data;   
    }

    let offset = 0;
    let pkg_head = qspkg.read_pkg_head(this.last_pkg, offset);
    if (!pkg_head.type) {
        if (pkg_head.offset >= this.last_pkg.length) {
            this.last_pkg = null;
        } else if (pkg_head.offset > offset) {
            const buf = Buffer.allocUnsafe(this.last_pkg.length - pkg_head.offset);
            this.last_pkg.copy(buf, 0, pkg_head.offset, this.last_pkg.length);
            this.last_pkg = buf;
        }
        return;
    }

    while(pkg_head.offset + pkg_head.len <= this.last_pkg.length) { // 判断是否有完整的包;
        if (pkg_head.len > 0) {
            // 根据长度信息来读取我们的数据,架设我们穿过来的是文本数据
            const pkg_data = Buffer.allocUnsafe(pkg_head.len);
            this.last_pkg.copy(pkg_data, 0, pkg_head.offset, pkg_head.offset + pkg_head.len);
            this.dispathData(pkg_head.type, pkg_data);
        } else {
            this.dispathData(pkg_head.type);
        }
        offset = pkg_head.offset + pkg_head.len;
        if (offset >= this.last_pkg.length) { // 正好我们的包处理完了;
            break;
        }
        pkg_head = qspkg.read_pkg_head(this.last_pkg, offset);
        if (!pkg_head.type) {
            offset = pkg_head.offset;
            break;
        }
    }
    if (offset >= this.last_pkg.length) {
        this.last_pkg = null;
    } else if (offset > 0) {
        const buf = Buffer.allocUnsafe(this.last_pkg.length - offset);
        this.last_pkg.copy(buf, 0, offset, this.last_pkg.length);
        this.last_pkg = buf;
    }
}

3、qspgk 根据协议处理数据

读取包头部分
    // 根据封包协议我们读取包头;
    read_pkg_head: function(pkg_data, offset) {
        const head = {};
        while (offset + qspkg.HEAD_LEN <= pkg_data.length) {
            const q = pkg_data.readUInt8(offset);
            const s = pkg_data.readUInt8(offset + 1);
            const type = pkg_data.readUInt8(offset + 2);
            const len = pkg_data.readUInt16LE(offset + 3);
            const code = pkg_data.readUInt8(offset + 5);
            if (q !== FLAG_Q || s !== FLAG_S) {
                offset++;
                head.offset = offset;
            } else if (qspkg.calc_head_sum(pkg_data, offset) !== code) {
                offset++;
                head.offset = offset;
            } else {
                head.type = type;
                head.offset = offset + qspkg.HEAD_LEN;
                head.len = len;
                break;
            }
        }
        return head;
    }
封装包头和数据
    // 把一个要发送的数据,封包 包头 + 数据
    // data string 二进制的buffer
    package_data: function(type, data) {
        const data_len = data ? data.length : 0;
        const buf = Buffer.allocUnsafe(qspkg.HEAD_LEN + data_len);
        buf.writeUInt8(FLAG_Q, 0);
        buf.writeUInt8(FLAG_S, 1);
        buf.writeUInt8(type, 2);
        buf.writeUInt16LE(data_len, 3);
        buf.writeUInt8(qspkg.calc_head_sum(buf, 0), 5);
        if (data_len > 0) {
            buf.fill(data, qspkg.HEAD_LEN);
        }
        return buf;
    }

你可能感兴趣的:(nodejs仿照WebSocket实现QuickSocket实时通讯框架)