pinusmod-kcp
Version:
kcp 的 connector (基于 node-kcp-x)
90 lines (89 loc) • 3.08 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeartbeatCommand = void 0;
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));
/**
* Process heartbeat request.
*
* @param {Object} opts option request
* opts.heartbeat heartbeat interval
*/
class HeartbeatCommand {
constructor(opts) {
this.timeouts = {};
this.clients = {};
opts = opts || {};
this.disconnectOnTimeout = opts.disconnectOnTimeout;
if (opts.heartbeat) {
this.heartbeat = opts.heartbeat * 1000; // heartbeat interval
this.timeout = opts.timeout * 1000 || this.heartbeat * 2; // max heartbeat message timeout
this.disconnectOnTimeout = true;
}
}
handle(socket) {
if (!this.heartbeat) {
// no heartbeat setting
return;
}
let self = this;
if (!this.clients[socket.id]) {
// clear timers when socket disconnect or error
this.clients[socket.id] = 1;
socket.once('disconnect', this.clearTimers.bind(this, socket.id));
socket.once('error', this.clearTimers.bind(this, socket.id));
}
// clear timeout timer
if (self.disconnectOnTimeout) {
this.clear(socket.id);
}
socket.sendRaw(pinusmod_protocol_1.Package.encode(pinusmod_protocol_1.Package.TYPE_HEARTBEAT));
if (self.disconnectOnTimeout) {
self.timeouts[socket.id] = setTimeout(function () {
logger.info('client %j heartbeat timeout.', socket.id);
socket.disconnect();
}, self.timeout);
}
}
clear(id) {
let tid = this.timeouts[id];
if (tid) {
clearTimeout(tid);
delete this.timeouts[id];
}
}
clearTimers(id) {
delete this.clients[id];
let tid = this.timeouts[id];
if (tid) {
clearTimeout(tid);
delete this.timeouts[id];
}
}
reset(socket) {
if (!this.heartbeat) {
// no heartbeat setting
return;
}
let self = this;
if (!this.clients[socket.id]) {
// clear timers when socket disconnect or error
this.clients[socket.id] = 1;
socket.once('disconnect', this.clearTimers.bind(this, socket.id));
socket.once('error', this.clearTimers.bind(this, socket.id));
}
// clear timeout timer
if (self.disconnectOnTimeout) {
this.clear(socket.id);
}
if (self.disconnectOnTimeout) {
self.timeouts[socket.id] = setTimeout(function () {
logger.info('client %j heartbeat timeout.', socket.id);
socket.disconnect();
}, self.timeout);
}
}
}
exports.HeartbeatCommand = HeartbeatCommand;