sync/src/io/backend/frontendmanager.js

63 lines
2.1 KiB
JavaScript
Raw Normal View History

2015-12-26 15:07:03 -08:00
import ioServer from '../ioserver';
import ProxiedSocket from './proxiedsocket';
2015-12-24 16:24:07 -08:00
export default class FrontendManager {
2015-12-26 15:07:03 -08:00
constructor(socketEmitter) {
this.socketEmitter = socketEmitter;
2015-12-24 16:24:07 -08:00
this.frontendConnections = {};
2015-12-26 15:07:03 -08:00
this.frontendProxiedSockets = {};
2015-12-24 16:24:07 -08:00
}
onConnection(socket) {
2015-12-26 15:07:03 -08:00
if (this.frontendConnections.hasOwnProperty(socket.remoteAddressAndPort)) {
2015-12-24 16:24:07 -08:00
// TODO: do some validation, maybe check if the socket is still connected?
throw new Error();
}
this.frontendConnections[socket.remoteAddressAndPort] = socket;
socket.on('data', this.onData.bind(this, socket));
}
onData(socket, data) {
2015-12-26 15:07:03 -08:00
switch (data.$type) {
case 'socketConnect':
this.onSocketConnect(socket, data);
break;
case 'socketFrame':
this.onSocketFrame(socket, data);
break;
}
}
onSocketConnect(frontendConnection, data) {
const mapKey = frontendConnection.remoteAddressAndPort;
const proxiedSocket = new ProxiedSocket(
data.socketID,
data.socketData,
this.socketEmitter,
frontendConnection);
if (!this.frontendProxiedSockets.hasOwnProperty(mapKey)) {
this.frontendProxiedSockets[mapKey] = {};
} else if (this.frontendProxiedSockets[mapKey].hasOwnProperty(data.socketID)) {
// TODO: Handle this gracefully
throw new Error();
}
this.frontendProxiedSockets[mapKey][data.socketID] = proxiedSocket;
ioServer.handleConnection(proxiedSocket);
}
onSocketFrame(frontendConnection, data) {
const mapKey = frontendConnection.remoteAddressAndPort;
const socketMap = this.frontendProxiedSockets[mapKey];
if (!socketMap || !socketMap.hasOwnProperty(data.socketID)) {
// TODO
throw new Error();
}
const socket = socketMap[data.socketID];
socket.onProxiedEventReceived.apply(socket, [data.event].concat(data.args));
2015-12-24 16:24:07 -08:00
}
}