-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_server.js
33 lines (26 loc) · 1023 Bytes
/
tcp_server.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
const net = require('net'); // Import the net module for TCP communication
// Configuration for the TCP server
const PORT = 3001; // The port to listen on
const HOST = '127.0.0.1'; // The host (localhost)
// Create a TCP server
const server = net.createServer((socket) => {
console.log('Client connected');
// Event: When the server receives data from the client
socket.on('data', (data) => {
console.log('Received from client:', data.toString());
// Optionally, echo the data back to the client
socket.write('Echo: ' + data.toString());
});
// Event: When the client disconnects
socket.on('end', () => {
console.log('Client disconnected');
});
// Event: When an error occurs with the connection
socket.on('error', (err) => {
console.error('Socket error:', err.message);
});
});
// Start the server to listen on the specified port and host
server.listen(PORT, HOST, () => {
console.log(`TCP server running on ${HOST}:${PORT}`);
});