-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (46 loc) · 1.73 KB
/
Copy pathserver.js
File metadata and controls
60 lines (46 loc) · 1.73 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
const WebSocket = require('ws');
const express = require('express');
const http = require('http');
// Create an Express app
const app = express();
// Create an HTTP server using Express (this allows us to add health check route)
const server = http.createServer(app);
// Create a WebSocket server using the same HTTP server
const wss = new WebSocket.Server({ server }); // { port: 8080 }
// WebSocket server
wss.on('connection', function (wsConnection) {
console.log('Client connected');
wsConnection.on('message', function (message) {
console.log(`Server received message: ${message}`);
});
wsConnection.send('Got your message!');
// Handle client disconnecting
wsConnection.on('close', function () {
console.log('Client disconnected');
});
});
// Health check route (to test if the server is deployed)
app.get('/health', (req, res) => {
res.status(200).send('WebSocket server is running!');
});
// Start the HTTP server (which also handles WebSocket connections)
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
console.log(`WebSocket server is running on ws://localhost:${PORT}`);
console.log(`Health check available at http://localhost:${PORT}/health`);
});
// FE
// const socket = new WebSocket('ws://localhost:8080');
// socket.addEventListener('open', function (event) {
// socket.send('Hello Server!');
// });
// socket.addEventListener('message', function (event) {
// console.log('Message from server ', event.data);
// });
// socket.addEventListener('close', function (event) {
// console.log('The connection has been closed');
// });
// Event listener for WebSocket errors
// socket.addEventListener('error', function (event) {
// console.error('WebSocket error observed:', event);
// });