avocado-old/packages/client/socket.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import io from 'socket.io-client';
import {compose} from '@avocado/core';
import {EventEmitter} from '@avocado/mixins';
2019-04-11 15:26:13 -05:00
import {SocketIoParser, allPackets, idFromPacket} from '@avocado/packet';
2019-03-17 23:45:48 -05:00
const decorate = compose(
EventEmitter,
);
class SocketClient extends decorate(class {}) {
2019-03-17 23:45:48 -05:00
2019-04-12 12:09:05 -05:00
constructor(address, options = {}) {
2019-03-17 23:45:48 -05:00
super();
this.isConnected = false;
2019-03-17 23:45:48 -05:00
this.socket = io(address, {
2019-04-11 15:26:13 -05:00
parser: SocketIoParser,
2019-03-17 23:45:48 -05:00
path: '/avocado',
2019-04-12 00:09:25 -05:00
perMessageDeflate: false,
2019-04-12 12:09:05 -05:00
...options,
2019-03-17 23:45:48 -05:00
});
this.socket.on('connect', () => {
this.isConnected = true;
2019-03-17 23:45:48 -05:00
this.emit('connect');
});
this.socket.on('disconnect', () => {
this.isConnected = false;
this.emit('disconnect');
});
2019-04-11 15:26:13 -05:00
for (const Packet of allPackets()) {
const id = idFromPacket(Packet);
this.socket.on(id, (packet) => {
this.emit('packet', packet);
});
2019-03-17 23:45:48 -05:00
}
}
2019-04-11 15:26:13 -05:00
send(packet) {
const id = idFromPacket(packet.constructor);
this.socket.emit(id, packet.data);
2019-03-17 23:45:48 -05:00
}
}
export function create(address) {
return new SocketClient(address);
}