UNPKG

awv3

Version:
79 lines (69 loc) 2.69 kB
import io from 'socket.io-client'; import Base from './base'; import Parser from '../core/parser'; import { createContext, handleResult } from '../core/parser'; export default class SocketIO extends Base { constructor(options) { super(options); } connect(url = this.url, options) { return new Promise((resolve, reject) => { this.url = url; this.socket = io(url); this.socket.once('connect', () => { this.socket.once('permission', data => { this.connected = true; this.id = data.id; this.emit('connected', this, data); resolve(this); }); this.socket.emit('init', options || this.options); }); this.socket.on('connect_error', reason => { this.emit('error', reason); reject(reason); }); this.socket.on('connect_timeout', reason => { this.emit('error', reason); reject(reason); }); let current = undefined; this.socket.on('binary', (data, flags) => { SocketIO._ack(this.socket); if (current) { handleResult(current, new Uint8Array(data)); } }); this.socket.on('json', data => { SocketIO._ack(this.socket); if (data.from === 'BeginFrame') current = this.tasks.get(data.transactionID); if (current) handleResult(current, data); if (current && data.from === 'EndFrame' && data.transactionID === current.id) { this.tasks.delete(current.id); current = undefined; } }); }); } disconnect() { this.socket.disconnect(); this.socket = undefined; this.tasks = new Map(); this.emit('disconnected', this); } request(command, factory = {}) { return new Promise((resolve, reject) => { let context = createContext(factory, resolve, reject, command); context.options.callback({ type: Parser.Factory.Started, context }); this.tasks.set(context.id, context); this.socket.emit('send', context.id, command, factory.classcad); }).then(results => { results.options.callback({ type: Parser.Factory.Finished, context: results }); return results; }); } static _ack(socket) { //if (socket.io.engine.transport.name !== 'websocket'); socket && socket.emit('received'); } }