send a message to a tcp server in typescript

To send a message to a TCP server in TypeScript, we can use the built-in net module in Node.js which provides an asynchronous network API.

First, we need to create a new net.Socket object and connect it to the server:

index.ts
import net from 'net';

const client = new net.Socket();

client.connect(8080, 'localhost', () => {
  console.log('Connected to server');
});
142 chars
8 lines

In this example, we connect to a server running on localhost at port 8080. Once the connection is established, the connect event is emitted and we can send data to the server.

To send a message, we simply use the write method on the client object:

index.ts
client.write('Hello, server!');
32 chars
2 lines

This will send the message "Hello, server!" to the server.

The write method automatically serializes the data as a byte stream, so we can send any type of data as long as it can be serialized to bytes.

Finally, we can listen for the data event to receive any messages sent back from the server:

index.ts
client.on('data', (data) => {
  console.log('Received message from server:', data.toString());
});
99 chars
4 lines

This will print out any messages received from the server as a string. We can also use the end method to close the socket once we're done communicating with the server:

index.ts
client.end();
14 chars
2 lines

And that's it! We have successfully sent a message to a TCP server in TypeScript using Node.js.

gistlibby LogSnag