-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
78 lines (66 loc) · 2.06 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* @file index.js
* @description This file contains the main entry point for the showdown server.
* @author Areeb Islam
*/
import PROJECT_CONFIG from './config';
import { ParseResponseData } from './data_parser';
import dotenv from 'dotenv';
import websocket from 'websocket';
import express from 'express';
import http from 'http';
import { WebSocketServer } from 'ws';
dotenv.config();
var WebSocketClient = websocket.client;
var client = new WebSocketClient();
globalThis.Connection = null;
// TODO change this assertion from being a global variable to a function
globalThis.Assertion = null;
client.on('connectFailed', function (error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function (connection) {
globalThis.Connection = connection;
connection.on('error', function (error) {
console.log('Connection Error: ' + error.toString());
});
connection.on('close', function () {
console.log('echo-protocol Connection Closed');
});
connection.on('message', function (message) {
// Process the message into a json object
console.log('Server Message', message);
if (message.type === 'utf8') {
ParseResponseData(message);
}
});
});
client.connect(PROJECT_CONFIG.url);
const app = express();
const server = http.createServer(app);
// Instantiates a websocket server
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
});
wss.on('connection', (ws) => {
PROJECT_CONFIG.clients.add(ws);
console.log(
'Connection Established with Client',
PROJECT_CONFIG.clients.size
);
ws.on('message', (msg) => {
if (msg.toString() !== '' && globalThis.Connection !== null) {
globalThis.Connection.send(msg.toString());
}
});
ws.on('close', () => {
console.log('Connection Closed with Client');
PROJECT_CONFIG.clients.delete(ws);
});
});
server.listen(PROJECT_CONFIG.port, () => {
console.log(`Server listening on port ${PROJECT_CONFIG.port}`);
});