Skip to content

Commit

Permalink
feat: add basic websocket server
Browse files Browse the repository at this point in the history
This will handle all stuff to do with websockets
  • Loading branch information
TGRHavoc committed Jun 9, 2019
1 parent 64ff008 commit 5bbee05
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/server.js
@@ -1,12 +1,14 @@
const Koa = require("koa");
const koaBody = require("koa-body");
const Router = require("koa-router");
const WS = require("ws");
const http = require("http");
const logger = require("simple-console-logger");

const app = new Koa();
const server = http.createServer(app.callback());
const router = new Router();
const wss = new WS.Server({ server });

const debugLevel = GetConvar("livemap_debug_level", "warn");
const access = GetConvar("livemap_access_control", "*");
Expand All @@ -23,6 +25,8 @@ router.use(async (ctx, next) => {
});

require("./src/blips")(router);
require("./src/sockets")(wss, access);

app.use(koaBody({
patchKoa: true,
}))
Expand Down
27 changes: 27 additions & 0 deletions src/sockets.js
@@ -0,0 +1,27 @@
const log = require("simple-console-logger").getLogger("LiveMap Sockets");
const WS = require("ws");

const SocketController = (wss, access) => {
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WS.OPEN) {
client.send(data);
}
});
};

wss.on("connection", function connection(ws, req) { //ws, res
log.trace("Access is: %s", access);
if (access !== "*") { // We don't want to accept all requests
if (req.headers.origin !== access) {
ws.close();
log.warn("Someone tried connecting from an invalid origin: %s", req.headers.origin);
}
}
log.debug("connection made from", req.headers.origin);
});

return {};
};

module.exports = SocketController;

0 comments on commit 5bbee05

Please sign in to comment.