-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsimple-test-server.js
More file actions
98 lines (85 loc) · 2.45 KB
/
Copy pathsimple-test-server.js
File metadata and controls
98 lines (85 loc) · 2.45 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* eslint-disable no-console */
import { readFileSync } from "node:fs";
// Simple WebSocket test server
import { createServer } from "node:http";
import { dirname, join } from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import { WebSocketServer } from "ws";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const server = createServer((req, res) => {
console.log(`HTTP ${req.method} ${req.url}`);
if (req.url === "/") {
const html = readFileSync(join(__dirname, "e2e", "test-page.html"), "utf8");
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html);
} else if (req.url === "/debug") {
const html = readFileSync(join(__dirname, "debug-test.html"), "utf8");
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html);
} else if (req.url === "/websocket-client.js") {
const bundle = readFileSync(
join(__dirname, "dist", "index.browser.mjs"),
"utf8",
);
res.writeHead(200, {
"Content-Type": "application/javascript; charset=utf-8",
"Access-Control-Allow-Origin": "*",
});
res.end(bundle);
} else {
res.writeHead(404);
res.end("Not Found");
}
});
const wss = new WebSocketServer({
server,
path: "/ws",
});
wss.on("connection", (ws, req) => {
console.log("WebSocket connection established");
ws.on("message", (data) => {
const text = data.toString();
console.log("Received:", text);
try {
const msg = JSON.parse(text);
// Echo the message back with some modifications
const response = {
type: msg.type,
payload: msg.payload,
timestamp: Date.now(),
echo: true,
};
ws.send(JSON.stringify(response));
} catch (error) {
console.error("Message parse error:", error);
ws.send(
JSON.stringify({
type: "error",
message: "Invalid JSON",
}),
);
}
});
ws.on("close", () => {
console.log("WebSocket connection closed");
});
ws.on("error", (error) => {
console.error("WebSocket error:", error);
});
});
const port = 3000;
server.listen(port, () => {
console.log(
`Simple WebSocket test server running on http://localhost:${port}`,
);
console.log(`WebSocket endpoint: ws://localhost:${port}/ws`);
});
// Graceful shutdown
process.on("SIGINT", () => {
console.log("Shutting down server...");
server.close(() => {
process.exit(0);
});
});