简体   繁体   中英

Listen for UDP messages in Express

I have a basic Node.js server using Express. It needs to be able to handle TCP messages as well as UDP messages. The TCP part is up and running great, but now I need to integrate a way to sniff out the UDP messages. I've tried adding a handler to the filter stack using a dgram socket, but it hasn't been successful.

const express = require('express');
const dgram = require('dgram');

// ...

const app = express();
const dgramSocket = dgram.createSocket('udp4');

// ...

app.use((req, res, next) => {
  dgramSocket.on('listening', () => {
    let addr = app.address();
    console.log(`Listening for UDP packets at ${addr.address}:${addr.port}`);
  });

  dgramSocket.on('error', (err) => {
    console.log(`UDP error: ${err.stack}`);
  });

  dgramSocket.on('message', (msg, rinfo) => {
    console.log(`Received UDP message`);
  });

  next();

}

// ...

app.set('port', 8080);

When I run my server everything else works, but my dgram parts don't even say that they're listening. I'm not too familiar with Node and even less so with UDP, so I might be on the complete wrong track. Has anyone been able to integrate UDP messaging with an Express server?

Looks like I made some unfortunate assumptions about the usage of ports. It turns out this can be done quite simply, but you have to listen on two different ports:

const express = require('express');
const dgram = require('dgram');

// ...

const app = express();

// ... filter stack ...

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

socket.on('listening', () => {
  let addr = socket.address();
  console.log(`Listening for UDP packets at ${addr.address}:${addr.port}`);
});

socket.on('error', (err) => {
  console.error(`UDP error: ${err.stack}`);
});

socket.on('message', (msg, rinfo) => {
  console.log('Recieved UDP message');
});

app.set('port', 8080); // listen for TCP with Express
socket.bind(8082);     // listen for UDP with dgram

Works like a charm.

Where do you bind the socket to a port? Docs: https://nodejs.org/api/dgram.html#dgram_socket_bind_port_address_callback

Try calling dgramSocket.bind(PORT) at the bottom of the code and see if triggers your console log. You will (probably) have to move the socket code outside of the app.use() function.

If you're just going to be sending messages from the socket, then I don't think you need to bind it to a port, but if you're listening you need to tell it where to listen at.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM