pinusmod-kcp2
Version:
kcp 的 connector,基于 kcpjs
83 lines (82 loc) • 3 kB
JavaScript
"use strict";
/**
* Copyright 2016 leenjewel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Connector = void 0;
const events_1 = require("events");
const kcpsocket_1 = require("./kcpsocket");
const pinuscoder = require("./pinuscoder");
const pinusmod_1 = require("pinusmod");
const coder = require("../common/coder");
const kcpjs_1 = require("kcpjs");
let curId = 1;
class Connector extends events_1.EventEmitter {
constructor(port, host, opts) {
super();
this.opts = opts || {};
this.host = host;
this.port = port;
this.useDict = opts.useDict;
this.useProtobuf = opts.useProtobuf;
this.clientsForKcp = {};
}
start(cb) {
const app = this.opts.app || pinusmod_1.pinus.app;
this.connector = app.components.__connector__.connector;
this.dictionary = app.components.__dictionary__;
this.protobuf = app.components.__protobuf__;
this.decodeIO_protobuf = app.components.__decodeIO__protobuf__;
this.on('disconnect', (kcpsocket) => {
this.listener.closeSession(kcpsocket.sess.key);
const conv = kcpsocket.opts.conv;
delete this.clientsForKcp[conv];
});
this.listener = (0, kcpjs_1.ListenWithOptions)({
port: this.port,
dataShards: this.opts.dataShards,
parityShards: this.opts.parityShards,
block: this.opts.block,
callback: (sess) => {
const conv = sess.getConv();
let kcpsocket = this.clientsForKcp[conv];
if (!kcpsocket) {
kcpsocket = new kcpsocket_1.KcpSocket(curId++, sess, { ...this.opts, conv });
this.clientsForKcp[conv] = kcpsocket;
pinuscoder.setupHandler(this, kcpsocket, this.opts);
this.emit('connection', kcpsocket);
}
},
});
process.nextTick(cb);
}
static decode(msg) {
return coder.decode.bind(this)(msg);
}
decode(msg) {
return Connector.decode(msg);
}
static encode(reqid, route, msg) {
return coder.encode.bind(this)(reqid, route, msg);
}
encode(reqid, route, msg) {
return Connector.encode(reqid, route, msg);
}
stop(force, cb) {
this.listener.close();
process.nextTick(cb);
}
}
exports.Connector = Connector;