create a tcp client on a specific port in typescript

Here's an example of how to create a TCP client in TypeScript using Node.js:

index.ts
import * as net from 'net';

const PORT = 8080;
const HOST = 'localhost';

const client = new net.Socket();

client.connect(PORT, HOST, () => {
  console.log('Connected');

  // Send data to the server
  client.write('Hello, server!');

  // Listen for data from the server
  client.on('data', (data: Buffer) => {
    console.log(`Received: ${data}`);
  });

  // Close the socket when the server closes the connection
  client.on('close', () => {
    console.log('Connection closed');
  });
});

// Handle errors
client.on('error', (error: Error) => {
  console.error(`Error: ${error}`);
});
593 chars
29 lines

In this example, we import the Node.js net module, set the PORT and HOST constants to the desired values, create a new net.Socket instance, and then connect to the server using the connect() method.

Once connected, we can send data to the server using the write() method and listen for data from the server using the on('data') method. We also handle the close and error events to properly close the socket and handle any errors that may occur.

gistlibby LogSnag