avocado-old/packages/client/socket.js

35 lines
759 B
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import {EventEmitter} from 'events';
import io from 'socket.io-client';
2019-04-11 15:26:13 -05:00
import {SocketIoParser, allPackets, idFromPacket} from '@avocado/packet';
2019-03-17 23:45:48 -05:00
class SocketClient extends EventEmitter {
constructor(address) {
super();
this.socket = io(address, {
2019-04-11 15:26:13 -05:00
parser: SocketIoParser,
2019-03-17 23:45:48 -05:00
path: '/avocado',
});
this.socket.on('connect', () => {
this.emit('connect');
});
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);
}