Created
May 6, 2016 14:48
-
-
Save copygirl/145d5d00bb5113c268d7540b6facf496 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Server as WebSocketServer } from "uws"; | |
| import winston from "winston"; | |
| import Client from "./Client"; | |
| import { AsyncEventEmitter } from "../../common/utility"; | |
| const defaultOptions = { | |
| wssOptions: { | |
| port: 8080 | |
| } | |
| }; | |
| export const State = Object.freeze({ | |
| READY: "READY", | |
| STARTING: "STARTING", | |
| RUNNING: "RUNNING", | |
| STOPPING: "STOPPING", | |
| STOPPED: "STOPPED" | |
| }); | |
| export const Events = Object.freeze({ | |
| STARTING: "server:starting", | |
| STARTED: "server:started", | |
| STOPPING: "server:stopping", | |
| STOPPED: "server:stopped" | |
| }); | |
| export default class Server extends AsyncEventEmitter { | |
| constructor(options = { }) { | |
| super(Object.assign({ }, defaultOptions, options)); | |
| this.state = State.READY; | |
| this.wss = null; | |
| this.clients = new Set(); | |
| } | |
| async start() { | |
| if ((this.state != State.READY) && (this.state != State.STOPPED)) | |
| throw new Error(`Can't start server while state is ${ this.state }`); | |
| this.logger.info("Starting up METATON ..."); | |
| await this.emit(Events.STARTING); | |
| this.logger.info("Starting WebSocket Server ..."); | |
| this.wss = new WebSocketServer(this.options.wssOptions); | |
| this.wss.on("connection", (ws) => clientConnected.call(this, ws)); | |
| this.logger.info("Finalizing METATON startup ..."); | |
| await this.emit(Events.STARTED); | |
| this.logger.info("METATON ready to rock!"); | |
| } | |
| async stop() { | |
| if (this.state != State.RUNNING) | |
| throw new Error(`Can't stop server while state is ${ this.state }`); | |
| this.logger.info("Stopping METATON gracefully ..."); | |
| await this.emit(Events.STOPPING); | |
| this.wss.close(); | |
| this.wss = null; | |
| this.logger.info("Finalizing METATON shutdown ..."); | |
| await this.emit(Events.STOPPED); | |
| this.logger.info("METATON ready to chill."); | |
| } | |
| } | |
| function clientConnected(ws) { | |
| const client = new Client(this, ws); | |
| this.clients.add(client); | |
| client.on(Client.Events.DISCONNECTED, | |
| () => this.clients.delete(client)); | |
| for (const event of Object.values(Client.Events)) | |
| client.on(event, (...args) => this.emit(client, ...args)); | |
| this.emit(Client.Events.CONNECTED, client); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment