在 Express 中侦听 UDP 消息 [英] Listen for UDP messages in Express

查看:17
本文介绍了在 Express 中侦听 UDP 消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Express 的基本 Node.js 服务器.它需要能够处理 TCP 消息以及 UDP 消息.TCP 部分已启动并运行良好,但现在我需要集成一种方法来嗅探 UDP 消息.我尝试使用 dgram 套接字将处理程序添加到过滤器堆栈,但没有成功.

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);

当我运行我的服务器时,其他一切都正常工作,但我的 dgram 部分甚至没有说他们正在监听.我对 Node 不太熟悉,对 UDP 更不熟悉,所以我可能完全走错了路.有没有人能够将 UDP 消息传递与 Express 服务器集成?

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

像魅力一样工作.

这篇关于在 Express 中侦听 UDP 消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆