Poco C++ 1.4.3p1 的 DatagramSocket ReceiveBytes() 永远不会返回。我是否滥用了该功能?

Poco C++ 1.4.3p1's DatagramSocket ReceiveBytes() never returns. Am I misusing the function?

本文关键字:是否 返回 功能 3p1 C++ DatagramSocket 永远 ReceiveBytes Poco      更新时间:2023-10-16

我刚刚开始使用Poco库。我在让两台计算机使用 Poco 的数据报套接字对象进行通信时遇到问题。具体来说,receiveBytes 函数似乎没有返回(尽管运行 Wireshark 并看到我发送的 UDP 数据包到达目标机器(。我假设我省略了一些简单的东西,这都是由于我的愚蠢错误。我已经使用Visual Studio Express 2010在Windows 7上编译了Poco 1.4.3p1。下面是显示我如何尝试使用 Poco 的代码片段。任何建议将不胜感激。

发送

#include "PocoNetDatagramSocket.h"
#include "Serializer.h" //A library used for serializing data
int main()
{
   Poco::Net::SocketAddress remoteAddr("192.168.1.140", 5678); //The IP address of the remote (receiving) machine
   Poco::Net::DatagramSocket mSock; //We make our socket (its not connected currently)
   mSock.connect(remoteAddr); //Sends/Receives are restricted to the inputted IPAddress and port
   unsigned char float_bytes[4];
   FloatToBin(1234.5678, float_bytes); //Serializing the float and storing it in float_bytes
   mSock.sendBytes((void*)float_bytes, 4); //Bytes AWAY!
   return 0;
}

接收(我遇到问题的地方(

#include "PocoNetDatagramSocket.h"
#include "PocoNetSocketAddress.h"
#include "Serializer.h"
#include <iostream>
int main()
{
   Poco::Net::SocketAddress remoteAddr("192.168.1.116", 5678); //The IP address of the remote (sending) machine
   Poco::Net::DatagramSocket mSock; //We make our socket (its not connected currently)
   mSock.connect(remoteAddr); //Sends/Receives are restricted to the inputted IPAddress and port
   //Now lets try to get some datas
   std::cout << "Waiting for float" << std::endl;
   unsigned char float_bytes[4];
   mSock.receiveBytes((void*)float_bytes, 4); //The code is stuck here waiting for a packet. It never returns...
   //Finally, lets convert it to a float and print to the screen
   float net_float;
   BinToFloat(float_bytes, &net_float); //Converting the binary data to a float and storing it in net_float
   std::cout << net_float << std::endl;
   system("PAUSE");
   return 0;
}

谢谢你的时间。

POCO 插座以伯克利插座为蓝本。您应该阅读有关Berkeley套接字API的基本教程,这将使您更容易理解POCO OOP套接字抽象。

您不能在客户端和服务器上连接((。您仅在客户端上连接((。对于UDP,connect((是可选的,可以跳过(然后你必须使用sendTo((而不是SendBytes(((。

在服务器上,要么在通配符 IP 地址上绑定(意思是:将在主机上所有可用的网络接口上接收(,要么绑定到特定的 IP 地址(意思是:然后仅在该 IP 地址上接收(。

查看您的接收器/服务器代码,似乎您想过滤远程客户端的地址。你不能用connect((来做,你必须用receiveFrom(buffer,length,address(读取,然后在"address"上过滤自己。

在安全方面,请注意您对收到的 UDP 数据包的源地址所做的假设。欺骗 UDP 数据包是微不足道的。换句话说:不要根据IP地址(或任何未通过适当加密保护的内容(做出身份验证或授权决策。

POCO 演示文稿 http://pocoproject.org/slides/200-Network.pdf 通过代码片段解释了如何使用 POCO 进行网络编程。请参阅幻灯片 15、16 了解 DatagramSocket。请注意,在第 15 张幻灯片上有一个拼写错误,将 msg.data((, msg.size(( 替换为 syslogMsg.data((, syslogMsg.size(( 进行编译 :-(

还可以查看"poco/net/samples"目录以获取简短的示例,这些示例还显示了使用POCO的最佳实践。