send a json message to a tcp server in typescript

To send a JSON message to a TCP server in TypeScript, you can use the built-in net module in Node.js. Here's an example code snippet:

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

// Create a socket connection to the server
const socket = net.createConnection({ port: 3000 }, () => {
  console.log("Connected to the server!");

  // Create a JSON message
  const message = JSON.stringify({
    foo: "bar",
    baz: 123,
  });

  // Send the message to the server
  socket.write(message, (err) => {
    if (err) {
      console.error(err);
    } else {
      console.log("Message sent successfully!");
    }

    // Close the socket connection when done
    socket.end();
  });
});

// Handle any errors or data received from the server
socket.on("error", (err) => {
  console.error(err);
});

socket.on("data", (data) => {
  console.log(`Received data from server: ${data}`);
});
729 chars
34 lines

In this example, we create a socket connection to a TCP server running on port 3000. Once the connection is established, we create a JSON message using JSON.stringify() and send it to the server using socket.write().

We also handle any errors that may occur during the connection or message sending process using callbacks. Finally, we close the socket connection using socket.end().

We also add event listeners to the socket object to handle any incoming data or errors from the server.

Note that this is a basic example and you may need to add additional error handling and data parsing logic depending on the requirements of your application.

gistlibby LogSnag