Skip to content

Instantly share code, notes, and snippets.

@MagnusThor
Created July 30, 2020 12:52
Show Gist options
  • Save MagnusThor/9564824dcc6385d736565973798cbef9 to your computer and use it in GitHub Desktop.
Save MagnusThor/9564824dcc6385d736565973798cbef9 to your computer and use it in GitHub Desktop.
Set up a ThorIO Server on Express
import path from "path";
import fs from "fs";
import http from "http";
import https from "https";
import express from "express";
import webSocket from "ws";
import { ExampleController } from "./controllers/ExampleController";
import { BrokerController } from "../src/Controllers/BrokerController/Broker";
import { ThorIO } from "..";
console.clear();
let rootPath = path.resolve(".");
let clientPath = path.join(rootPath, "example");
let port = +process.env.PORT;
port = port || 1337;
let httpServer: http.Server | https.Server;
let app = express();
// Create a new ThorIO Server (instance) ,register two controllers
let thorio = ThorIO.createInstance([ExampleController, BrokerController]);
// Set up route to the client served on express
if (fs.existsSync(clientPath)) {
console.log(`Serving client files from ${clientPath}.`);
app.use("/", express.static(clientPath));
} else {
console.log(`Serving no client files.`);
app.get("/", (_, res) => res.send("Kollokvium WebSocket Server is running"));
}
httpServer = http.createServer((req, res) => {
app(req, res);
});
const ws = new webSocket.Server({ server: httpServer });
// pass the WebSockets to the ThorIO instance
ws.on("connection", (ws, req) => {
console.log("..");
thorio.addWebSocket(ws, req)}
);
httpServer.listen(port);
console.log(`Server listening on ${port}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment