|
1 | 1 | // echo-server.js |
2 | | -const https = require("https"); |
3 | | -const fs = require("fs"); |
| 2 | +const http = require("http"); |
4 | 3 | const WebSocket = require("ws"); |
5 | 4 |
|
6 | | -const port = 4001; |
| 5 | +// Use Railway’s assigned port or default to 80. |
| 6 | +const port = process.env.PORT || 80; |
7 | 7 |
|
8 | | -// Read your TLS certificate and key |
9 | | -const serverOptions = { |
10 | | - key: fs.readFileSync("key.pem"), |
11 | | - cert: fs.readFileSync("cert.pem"), |
12 | | -}; |
13 | | - |
14 | | -// Create an HTTPS server using the certificate and key |
15 | | -const httpsServer = https.createServer(serverOptions); |
16 | | - |
17 | | -// Create the WebSocket server, binding it to the HTTPS server |
18 | | -const wss = new WebSocket.Server({ server: httpsServer }); |
| 8 | +// Create an HTTP server that can also handle upgrade requests. |
| 9 | +const server = http.createServer((req, res) => { |
| 10 | + res.writeHead(200, { "Content-Type": "text/plain" }); |
| 11 | + res.end("Hello, this is an HTTP server that supports WebSocket upgrades."); |
| 12 | +}); |
19 | 13 |
|
20 | | -httpsServer.listen(port, "0.0.0.0", () => { |
21 | | - console.log(`TLS Echo server listening on port ${port}`); |
| 14 | +server.listen(port, "0.0.0.0", () => { |
| 15 | + console.log(`HTTP/WebSocket server listening on port ${port}`); |
22 | 16 | }); |
23 | 17 |
|
| 18 | +// Bind the WebSocket server to the same HTTP server. |
| 19 | +const wss = new WebSocket.Server({ server }); |
| 20 | + |
24 | 21 | wss.on("connection", (ws) => { |
25 | 22 | console.log("Client connected"); |
26 | 23 | ws.on("message", (message) => { |
|
0 commit comments