Compare commits

..

1 Commits

Author SHA1 Message Date
6d6444e541 allows connections 2021-12-14 15:05:46 -06:00
4 changed files with 2550 additions and 2405 deletions

4856
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,8 @@
"scripts": {
"build": "tsc",
"start": "node .",
"watch": "npm-watch"
"watch": "npm-watch",
"dev": "npm-watch"
},
"watch": {
"build": {
@@ -29,7 +30,11 @@
"license": "ISC",
"devDependencies": {
"@types/node": "^16.11.12",
"@types/ws": "^8.2.2",
"npm-watch": "^0.11.0",
"typescript": "^4.5.3"
},
"dependencies": {
"ws": "^8.3.0"
}
}

33
src/connection.ts Normal file
View File

@@ -0,0 +1,33 @@
import WebSocket from 'ws';
//an individual connection
export class Connection {
private _ws: WebSocket;
private _data: initConnectData;
isAlive: boolean;
constructor(ws: WebSocket, data: initConnectData) {
this._ws = ws;
this._data = data;
this.isAlive = true;
ws.on('pong', () => this.isAlive = true);
}
public ping() {
this.isAlive = false;
this._ws.ping();
}
public terminate() {
this._ws.terminate();
}
}
//data sent to the server to initialize the connecction
export interface initConnectData {
id: string //change to allow login through discord
}

59
src/index.ts Normal file
View File

@@ -0,0 +1,59 @@
import WebSocket, { WebSocketServer } from 'ws';
import { Connection, initConnectData } from './connection';
const wss = new WebSocketServer({ port: 8001 }); //ill let nginx deal with https
//all current connections
const Connections: { [keys: string]: Connection } = {};
//new client joins
wss.on('connection', ws => {
ws.once('message', data => {
let dataJson: initConnectData;
try {
dataJson = JSON.parse(data.toString()) as initConnectData;
initConnection(ws, dataJson);
} catch (e) {
ws.terminate();
}
});
});
//verify data and add to connections list
function initConnection(ws: WebSocket, data: initConnectData) {
if (data.id in Connections) {
ws.terminate();
return;
}
Connections[data.id] = new Connection(ws, data);
}
//ensure all connections are alive
const interval = setInterval(() => {
for (let key in Connections) {
let conn = Connections[key];
if (conn.isAlive)
conn.ping();
else {
conn.terminate();
delete Connections[key];
}
}
}, 30000);
/*
1. connect to ws server
2. send `initConnectData` as a string (will change to login with discord)
*/