send a json message to a udp server in typescript

To send a JSON message to a UDP server in TypeScript, you can use the built-in dgram module to create a UDP client socket. Here's an example code snippet:

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

const udpClient = dgram.createSocket('udp4');

const serverAddress = '127.0.0.1';
const serverPort = 1234;

const messageObj = { key1: 'value1', key2: 42 };
const jsonStringified = JSON.stringify(messageObj);

udpClient.send(jsonStringified, serverPort, serverAddress, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.log('Message sent successfully');
  }
});
421 chars
18 lines

In this code, we first import the dgram module and create a UDP client socket using dgram.createSocket('udp4'). We then define the UDP server address and port we want to send the message to, as well as the message object we want to send.

We stringify the message object using JSON.stringify() so that it can be sent over the network as a string payload. Finally, we call udpClient.send() with the payload, server port and address, and a callback function that handles errors if any occur.

If the message is sent successfully, we log a success message to the console. Otherwise, we log the error message to the console.

gistlibby LogSnag