1// Include Nodejs' net module.
2const Net = require('net');
3// The port number and hostname of the server.
4const port = 8080;
5const host = 'localhost';
6
7// Create a new TCP client.
8const client = new Net.Socket();
9// Send a connection request to the server.
10client.connect({ port: port, host: host }), function() {
11 // If there is no error, the server has accepted the request and created a new
12 // socket dedicated to us.
13 console.log('TCP connection established with the server.');
14
15 // The client can now send data to the server by writing to its socket.
16 client.write('Hello, server.');
17});
18
19// The client can also receive data from the server by reading from its socket.
20client.on('data', function(chunk) {
21 console.log(`Data received from the server: ${chunk.toString()}.`);
22
23 // Request an end to the connection after the data has been received.
24 client.end();
25});
26
27client.on('end', function() {
28 console.log('Requested an end to the TCP connection');
29});
30