create a udp server in typescript

To create a UDP server in TypeScript, we need to start by importing the required modules from Node.js. After that, we will create a UDP socket and listen to a port for incoming messages.

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

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

server.on('message', (msg, rinfo) => {
  console.log(`Received message ${msg} from ${rinfo.address}:${rinfo.port}`);
});

server.on('listening', () => {
  const address = server.address();
  console.log(`UDP server listening on ${address.address}:${address.port}`);
});

server.bind(3000);
367 chars
15 lines

In the above code, we are using the dgram module to create a UDP socket. We are then listening to the message event, which is emitted every time a message is received on the socket. We are also listening to the listening event, which is emitted after the socket starts listening to the port.

Now, we can start the server by calling the bind method on the socket, passing in the port number we want to listen on.

Note: By default, Node.js creates a "socket" in a namespace that is only accessible by processes running on the same machine. To allow connections to this server from other machines, we need to specify 0.0.0.0 as the address to bind to instead of the default loopback address 127.0.0.1. E.g. server.bind(3000, "0.0.0.0").

gistlibby LogSnag