c++ - 如何在嵌入式设备上通过 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
我的问题是,为什么我不能将我的板绑定到特定端口。你有什么想法?先感谢您。
解决方案
MBED 声明socket.bind
为bind (const Host &me)
. 参数不是端口号,而是Host
实例。将其更改为
sock.bind(Host(IpAddr(), port));
推荐阅读
- c - 无法通过重复使用 fgets 来读取文件
- flutter - Flutter 多语言应用
- python - 如何重新激活 django 服务器?
- r - 为什么这个带有 lambda 函数的管道不返回一个矩阵?
- javascript - 如何在不添加内联样式的情况下从 div 中删除特定的 css?
- pyspark - spark如何应用“仅正确”加入?
- r - 如何将导入的图像与其他 R 图结合起来?
- systemd - 如何在计算机进入之前让 systemd 自动设置 /sys/power/image_size(为 0)
- azure-active-directory - 如何强制用户使用 MSAL 角度的两因素身份验证?
- reactjs - React-Player 无法正确调整视频大小