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.ts142 chars8 linesIn 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.ts32 chars2 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.ts99 chars4 linesThis 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.ts14 chars2 lines
And that's it! We have successfully sent a message to a TCP server in TypeScript using Node.js.
gistlibby LogSnag