1

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

发送

#include "Poco\Net\DatagramSocket.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 "Poco\Net\DatagramSocket.h"
#include "Poco\Net\SocketAddress.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;
}

感谢您的时间。

4

1 回答 1

3

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

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

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

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

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

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

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

于 2012-05-21T13:11:03.077 回答