Create server.js
Browse files- src/server.js +54 -0
src/server.js
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import http from 'http';
|
2 |
+
import { WebSocketServer } from 'ws';
|
3 |
+
import fs from 'fs';
|
4 |
+
import path from 'path';
|
5 |
+
import { fileURLToPath } from 'url';
|
6 |
+
import { handleTerminalConnection, setSharedTerminalMode } from './terminal.js';
|
7 |
+
|
8 |
+
const __filename = fileURLToPath(import.meta.url);
|
9 |
+
const __dirname = path.dirname(__filename);
|
10 |
+
|
11 |
+
// Config
|
12 |
+
setSharedTerminalMode(false); // Set this to false to allow a shared session
|
13 |
+
const port = 6060;
|
14 |
+
|
15 |
+
const server = http.createServer((req, res) => {
|
16 |
+
if (req.method === 'GET') {
|
17 |
+
const routeName = req.url.slice(1);
|
18 |
+
const assetObj = {
|
19 |
+
'': { file: "index.html", contentType: "text/html" },
|
20 |
+
'client.js': { file: "client.js", contentType: "text/javascript" }
|
21 |
+
}[routeName];
|
22 |
+
|
23 |
+
if (!assetObj) {
|
24 |
+
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
25 |
+
return res.end('Path not found');
|
26 |
+
}
|
27 |
+
|
28 |
+
const filePath = path.join(__dirname, assetObj.file);
|
29 |
+
|
30 |
+
fs.readFile(filePath, (err, data) => {
|
31 |
+
if (err) {
|
32 |
+
res.writeHead(500, { 'Content-Type': 'text/plain' });
|
33 |
+
res.end('Failed to load file');
|
34 |
+
} else {
|
35 |
+
res.writeHead(200, { 'Content-Type': assetObj.contentType });
|
36 |
+
res.end(data);
|
37 |
+
}
|
38 |
+
});
|
39 |
+
}
|
40 |
+
});
|
41 |
+
|
42 |
+
const wss = new WebSocketServer({ noServer: true });
|
43 |
+
|
44 |
+
wss.on('connection', handleTerminalConnection);
|
45 |
+
|
46 |
+
server.on('upgrade', (request, socket, head) => {
|
47 |
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
48 |
+
wss.emit('connection', ws, request);
|
49 |
+
});
|
50 |
+
});
|
51 |
+
|
52 |
+
server.listen(port, () => {
|
53 |
+
console.log(`HTTP and WebSocket server is running on port ${port}`);
|
54 |
+
});
|