UNPKG

@wishcore/wish-sdk

Version:

Wish API for node. Used for building Wish Apps.

67 lines 2.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SocketProtocol = void 0; const events_1 = require("events"); class SocketProtocol extends events_1.EventEmitter { constructor(socket) { super(); this.socket = socket; this.cur = 0; this.cntIn = 0; this.write = socket.write.bind(socket); this.expectBytes = 0; this.expectCallback = null; socket.on('readable', this.readable.bind(this)); socket.on('error', (err) => { if (typeof this.expectCallback === 'function') { this.expectCallback(err); } }); // socket.on('connect', function() { this.emit('connect', arguments); }); } expect(bytes, callback) { // console.log('Expecting:', bytes); this.expectBytes = bytes; this.expectCallback = callback; } kick() { } bytes() { return this.cur; } drop() { if (this.socket) { this.socket.removeListener('readable', this.readable); } this.expectBytes = 0; this.expectCallback = null; } close() { if (this.socket) { this.socket.removeListener('readable', this.readable); this.socket.end(); } this.expectBytes = 0; this.expectCallback = null; } readable() { let chunk; if (this.expectBytes) { while (null !== (chunk = this.socket.read(this.expectBytes))) { this.cntIn += chunk.length; if (this.expectCallback) { this.expectCallback(null, chunk); } else { console.log('Nothing expected, but got some data... waiting... data is lost', this.expectCallback); this.socket.removeListener('readable', this.readable); } } } else { console.log('Nothing expected, but got some data... waiting for next readable?!'); } } } exports.SocketProtocol = SocketProtocol; //# sourceMappingURL=protocol.js.map