Finish code

This commit is contained in:
Hri7566 2023-10-30 18:03:46 -04:00
parent 03b7c5b515
commit d73fbaec86
5 changed files with 188 additions and 161 deletions

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
{
"arrowParens": "avoid",
"trailingComma": "none",
"tabWidth": 4
}

View File

@ -19,7 +19,7 @@ class Client extends EventEmitter {
this.ws.on("open", () => {});
this.ws.addEventListener("close", (evt) => {
this.ws.addEventListener("close", evt => {
this.emit("disconnected");
setTimeout(() => {
@ -27,12 +27,12 @@ class Client extends EventEmitter {
}, 1000);
});
this.ws.addEventListener("error", (evt) => {
this.ws.addEventListener("error", evt => {
this.emit("wserror", evt);
this.ws.close();
});
this.ws.addEventListener("message", (evt) => {
this.ws.addEventListener("message", evt => {
try {
const str = evt.data.toString();
const msg = JSON.parse(str);
@ -63,7 +63,11 @@ class Client extends EventEmitter {
}
log(level, message) {
if (!this.isConnected()) return;
this.say({ m: "log", level, message });
}
broadcast(msg) {
this.say({ m: "broadcast", msg });
}
isConnected() {
@ -71,9 +75,16 @@ class Client extends EventEmitter {
}
bindEventListeners() {
this.on("log", (msg) => {
console.log(`[${msg.level}] ${msg.message}`);
this.on("log", msg => {
console.log(`[Server] [${msg.level}] ${msg.message}`);
});
setInterval(() => {
this.say({
m: "t",
e: Date.now()
});
}, 20000);
}
}

View File

@ -1,7 +1,5 @@
require("dotenv").config();
// TODO Make this repo a module
let isServer;
process.argv.forEach((val, index, array) => {
@ -22,4 +20,6 @@ if (isServer) {
const { Client } = require("./client");
const cl = new Client();
cl.connect();
cl.log("DEBUG", "hello");
}

View File

@ -2,7 +2,7 @@ const WebSocket = require("ws");
const { EventEmitter } = require("events");
function broadcast(msg) {
Server.wss.clients.forEach((ws) => {
Server.wss.clients.forEach(ws => {
ws.say(msg);
});
}
@ -15,14 +15,14 @@ function log(level, message) {
class Server {
static start() {
this.wss = new WebSocket.Server({
port: process.env.PORT || 10911,
port: process.env.PORT || 10911
});
this.wss.on("connection", (ws, req) => {
ws.preauth = new EventEmitter();
ws.evt = new EventEmitter();
ws.say = (msg) => {
ws.say = msg => {
ws.send(JSON.stringify(msg));
};
@ -47,28 +47,39 @@ class Server {
}
});
ws.preauth.on("hi", (msg) => {
ws.preauth.on("hi", msg => {
if (!msg.project) return;
ws.authed = true;
ws.project = msg.project;
});
ws.evt.on("log", (msg) => {
ws.evt.on("log", msg => {
if (!msg.level) return;
if (!msg.message) return;
log(msg.level, `From ${req.socket.remoteAddress}: ${msg.message}`);
log(
msg.level,
`From ${req.socket.remoteAddress}: ${msg.message}`
);
});
ws.evt.on("broadcast", (msg) => {
ws.evt.on("broadcast", msg => {
if (!msg.msg) return;
if (typeof msg.msg !== "object") return;
if (!msg.msg.m) return;
broadcast({
m: "broadcast",
msg: msg.msg,
msg: msg.msg
});
});
ws.evt.on("t", msg => {
ws.say({
m: "t",
t: Date.now(),
e: msg.e
});
});
});