首页 > 解决方案 > 如何在嵌入式设备上通过 UDP 接收数据

问题描述

目前我正在为 Mbed 项目开发 UDP 客户端脚本。我使用 B-L475E-IOT01A 开发板,想从另一个网络设备接收数据。

发送方(在另一台设备上)工作。我在我的电脑上用 python 脚本测试了它。

我有以下问题:我可以建立与网络的连接,并且可以使用该open()函数初始化一个 UDP 套接字。我的问题是,如果我尝试bind()将套接字连接到端口或套接字地址,我会得到nsapi_error_t代码-3002,这意味着“不支持的功能”。这是代码:

#include "UDPSocket.h"
#include "mbed.h"

const char SSID[] = "";
const char password[] = "";
const uint16_t Port = 37020;

UDPSocket socket;
WiFiInterface *wifi;
BufferedSerial pc(USBTX, USBRX, 115200);

int main() {
  pc.set_format(8, SerialBase::None, 1);

  wifi = WiFiInterface::get_default_instance();
  if (!wifi) {
    printf("ERROR: No WiFiInterface found.\n");
    return -1;
  }

  printf("\nConnecting to %s...\n", SSID);
  int ret = wifi->connect(SSID, password, NSAPI_SECURITY_WPA2);
  if (ret != 0) {
    printf("\nConnection error: %d\n", ret);
    return -1;
  }

  SocketAddress a;
  wifi->get_ip_address(&a);
  printf("IP: %s\n", a.get_ip_address());

  int returnable = 1;
  while (returnable != 0) {
    returnable = socket.open(wifi);
    printf("%d\r\n", returnable);
    wait_us(500000);
  }

  returnable = 1;
  while (returnable != 0) {
    returnable = socket.bind(Port);
    printf("%d\r\n", returnable);
    wait_us(500000);
  }

  while (1) {
    char message[500];
    int n = socket.recv(&message, sizeof(message));
    printf("%d\r\n", n);
    printf("%s", message);
    wait_us(100000);
  }
  wifi->disconnect();

  printf("\nDone\n");
}

出于安全原因,我删除了 wifi 数据。这是输出:

Connecting to ...
IP: 192.168.178.25
0
-3002

我的问题是,为什么我不能将我的板绑定到特定端口。你有什么想法?先感谢您。

标签: c++cudpstm32mbed

解决方案


MBED 声明socket.bindbind (const Host &me). 参数不是端口号,而是Host实例。将其更改为

sock.bind(Host(IpAddr(), port));

推荐阅读