send a message to a udp server in javascript

The following code shows how to send a message to a UDP server in JavaScript using the built-in dgram module:

index.tsx
const dgram = require('dgram');
const { networkInterfaces } = require('os'); // Optional, used for getting local IP address

const client = dgram.createSocket('udp4');
const serverPort = 12345; // Replace with your server's port
const serverIP = '10.0.0.2'; // Replace with your server's IP address
const message = 'Hello, server!'; // Replace with your message

// Get local IP address (optional)
const interfaces = networkInterfaces();
let localIP;
Object.keys(interfaces).forEach((iface) => {
  interfaces[iface].forEach((i) => {
    if (i.family === 'IPv4' && !i.internal) localIP = i.address;
  });
});

// Bind client to local IP address (optional)
client.bind(undefined, localIP, () => {
  console.log(`Client is listening on ${localIP}:${client.address().port}`);
});

// Send message to server
client.send(message, serverPort, serverIP, (error) => {
  if (error) console.error(error);
  else console.log(`Message "${message}" sent to server at ${serverIP}:${serverPort}`);
});
986 chars
28 lines

This code creates a UDP socket client and sends a message to a server with a specified IP address and port. It also includes an optional step to get the local IP address and bind the client to it.

gistlibby LogSnag