-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_server4.js
72 lines (58 loc) · 1.65 KB
/
tcp_server4.js
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
const net = require('net');
// List to keep track of connected clients
const clients = [];
//
// Function to broadcast a message to all clients
//
function broadcast(message, senderSocket) {
// Send the message to all clients except the sender
clients.forEach((client) => {
if (client !== senderSocket) {
client.write(message);
}
});
}
//
// Create a TCP server
//
const server = net.createServer((socket) => {
console.log('Client connected');
// Add the new client to the list of clients
clients.push(socket);
// Send a welcome message to the client
socket.write('Welcome to the TCP server!');
// Broadcast to other clients that a new client has joined
broadcast('A new client has joined.\n', socket);
//
// When the server receives data from the client, broadcast it
//
socket.on('data', (data) => {
console.log('Received from client:', data.toString());
// Broadcast the message to other clients
broadcast(data.toString(), socket);
});
//
// Handle client disconnection
//
socket.on('end', () => {
console.log('Client disconnected');
// Remove the client from the list
const index = clients.indexOf(socket);
if (index > -1) {
clients.splice(index, 1);
}
// Notify other clients that someone has disconnected
broadcast('A client has disconnected.\n', socket);
});
//
// Handle socket errors
//
socket.on('error', (err) => {
console.error('Socket error:', err.message);
});
});
// Bind the server to a port and start listening
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Node.js TCP Server is started. Listening on (127.0.0.1:${PORT})`);
});