UNPKG

pinusmod-kcp

Version:

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

63 lines (62 loc) 1.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const pinusmod_protocol_1 = require("pinusmod-protocol"); const pinusmod_logger_1 = require("pinusmod-logger"); const path = require("path"); let logger = (0, pinusmod_logger_1.getLogger)('pinus', path.basename(__filename)); let handlers = {}; let ST_INITED = 0; let ST_WAIT_ACK = 1; let ST_WORKING = 2; let ST_CLOSED = 3; let handleHandshake = function (socket, pkg) { if (socket.state !== ST_INITED) { return; } try { socket.emit('handshake', JSON.parse(pinusmod_protocol_1.Protocol.strdecode(pkg.body))); } catch (ex) { socket.emit('handshake', {}); } }; let handleHandshakeAck = function (socket, pkg) { if (socket.state !== ST_WAIT_ACK) { return; } socket.state = ST_WORKING; socket.emit('heartbeat'); }; let handleHeartbeat = function (socket, pkg) { if (socket.state !== ST_WORKING) { return; } socket.emit('heartbeat'); }; let handleData = function (socket, pkg) { if (socket.state !== ST_WORKING) { return; } if (!!socket.heartbeatOnData) { // 每次收到 package 都触发 heartbeat ,避免客户端没发 heartbeat 而导致掉线 socket.emit('heartbeatreset'); } socket.emit('message', pkg); }; handlers[pinusmod_protocol_1.Package.TYPE_HANDSHAKE] = handleHandshake; handlers[pinusmod_protocol_1.Package.TYPE_HANDSHAKE_ACK] = handleHandshakeAck; handlers[pinusmod_protocol_1.Package.TYPE_HEARTBEAT] = handleHeartbeat; handlers[pinusmod_protocol_1.Package.TYPE_DATA] = handleData; function default_1(socket, pkg) { let handler = handlers[pkg.type]; if (!!handler) { handler(socket, pkg); return 0; } else { logger.error('could not find handle invalid data package.'); socket.disconnect(); return 1; } } exports.default = default_1;