create a tcp client on a specific port in javascript

To create a TCP client in JavaScript, you can use the net module that is built into Node.js. Here's an example of how to create a TCP client that connects to a server on a specific port:

index.tsx
const net = require('net');

const HOST = 'localhost';
const PORT = 3000;

const client = new net.Socket();
client.connect(PORT, HOST, () => {
  console.log(`Connected to server at ${HOST}:${PORT}`);
});

client.on('data', (data) => {
  console.log(`Received data: ${data}`);
});

client.on('close', () => {
  console.log('Connection closed');
});
348 chars
18 lines

In this example, we first require the net module, set the HOST and PORT variables to the server's hostname and port number, and create a new net.Socket object.

We then call the connect method on the socket and pass in the server's port and hostname. This establishes a connection to the server.

Next, we add event listeners for the data and close events. The data event is fired when data is received from the server, and the close event is fired when the connection is closed.

You can use this client side-by-side with a server that is listening on the same port to send and receive data between them.

gistlibby LogSnag