Kano001 commited on
Commit
ff4613e
1 Parent(s): 971fc9c

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +19 -16
server.js CHANGED
@@ -1,24 +1,27 @@
1
- const { WebSocketServer } = require('ws');
2
 
3
- // Create a WebSocket server listening on port 443
4
- const sockserver = new WebSocketServer({ port: 443 });
5
 
6
- sockserver.on('connection', ws => {
7
- console.log('New client connected!');
8
- ws.send('connection established');
9
 
10
- ws.on('close', () => console.log('Client has disconnected!'));
 
11
 
12
- ws.on('message', data => {
13
- sockserver.clients.forEach(client => {
14
- console.log(`distributing message: ${data}`);
15
- client.send(`${data}`);
 
 
16
  });
17
- });
18
 
19
- ws.onerror = function () {
20
- console.log('websocket error');
21
- };
 
22
  });
23
 
24
- console.log(`WebSocket server listening on port 443`);
 
1
+ const WebSocket = require('ws');
2
 
3
+ // Create a WebSocket server listening on port 8080
4
+ const wss = new WebSocket.Server({ port: 8080 });
5
 
6
+ // Event listener for new connections
7
+ wss.on('connection', (ws) => {
8
+ console.log('New client connected');
9
 
10
+ // Send a message to the client when they connect
11
+ ws.send('Welcome to the WebSocket server!');
12
 
13
+ // Event listener for messages from the client
14
+ ws.on('message', (message) => {
15
+ console.log(`Received message: ${message}`);
16
+
17
+ // Echo the message back to the client
18
+ ws.send(`You said: ${message}`);
19
  });
 
20
 
21
+ // Event listener for client disconnects
22
+ ws.on('close', () => {
23
+ console.log('Client disconnected');
24
+ });
25
  });
26
 
27
+ console.log('WebSocket server is running on ws://localhost:8080');