UNPKG

pinusmod-kcp

Version:

kcp 的 connector (基于 node-kcp-x)

93 lines (92 loc) 3.22 kB
"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 dgram = require("dgram"); const events_1 = require("events"); const kcpsocket_1 = require("./kcpsocket"); const pinuscoder = require("./pinuscoder"); const pinusmod_1 = require("pinusmod"); const coder = require("../common/coder"); 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 = {}; this.socket = dgram.createSocket('udp4'); } 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.socket.on('message', (msg, peer) => { this.bindSocket(this.socket, peer.address, peer.port, msg); }); this.on('disconnect', (kcpsocket) => { const conv = kcpsocket.opts.conv; delete this.clientsForKcp[conv]; }); this.socket.on('error', (error) => { return; }); this.socket.bind(this.port); process.nextTick(cb); } bindSocket(socket, address, port, msg) { let conv, kcpsocket; if (msg) { const kcpHead = pinuscoder.kcpHeadDecode(msg); conv = kcpHead.conv; kcpsocket = this.clientsForKcp[conv]; } if (!kcpsocket && conv) { kcpsocket = new kcpsocket_1.KcpSocket(curId++, socket, address, port, Object.assign({ conv }, this.opts)); pinuscoder.setupHandler(this, kcpsocket, this.opts); this.clientsForKcp[conv] = kcpsocket; this.emit('connection', kcpsocket); } if (!!msg && !!kcpsocket) { kcpsocket.emit('input', msg); } } 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) { if (this.socket) { this.socket.close(); } process.nextTick(cb); } } exports.Connector = Connector;