从广播获得答案

时间:2016-04-28 15:05:08

标签: c++11 udp poco datagram

我正在使用Poco::Net::DatagramSocket实现WSDiscovery服务。 这是代码:

string OnvifCamera::_sendFullProbe_for_Discovery() const noexcept
{
    Poco::Net::DatagramSocket ss(Poco::Net::IPAddress::IPv4);
    Poco::Net::SocketAddress sa(global.getDiscoveryIP(), global.getDiscoveryPort()); //IP "239.255.255.250", port 3702
    try
    {
        auto msg = _createXML_for_FullProbe();//is the XML probe x discovery
        ss.sendTo(msg.data(), msg.size(), sa);
    }
    catch (const Poco::IOException& ex)
    {
        cerr<<"\nException: "<<ex.what()<<", "<<ex.displayText()<<endl;
        return string();
    }
    ss.setBroadcast(true);

    char buffer[4096];
    int n = ss.receiveBytes(buffer, sizeof(buffer));
    cout<<"Got "<<n<<" bytes"<<endl;
    ss.close();
    return string(buffer);
}

每台设备(IP Onvif摄像机)都会回答他的XML数据。

问题是,如果我有更多相机,我只能得到1个相机的答案。我怎样才能得到所有答案?

2 个答案:

答案 0 :(得分:1)

您只需拨打receiveBytes一次,这就是为什么您只能得到一个答案。

要接收多个单独的答案,您需要反复拨打receiveBytes,并且很可能实施超时,之后您会放弃等待接收更多答案(因为您可以&#39;知道apriori会有多少人。

答案 1 :(得分:0)

遵循@Alnitack的建议,这是代码(它有效):

vector<XMLString> OnvifDiscovery::_sendFullProbe_for_Discovery() noexcept
{
    vector<XMLString> cameras_XML;
    DatagramSocket ss(IPAddress::IPv4);
    SocketAddress sa(_global.getDiscoveryIP(), _global.getDiscoveryPort());
    try
    {
        auto msg = _createXML_for_FullProbe();
        ss.sendTo(msg.data(), msg.size(), sa);
    }
    catch (const IOException& ex)
    {
        cerr<<"\nException: "<<ex.what()<<", "<<ex.displayText()<<endl;
        return cameras_XML;
    }

    ss.setBroadcast(true);

    Poco::Timespan timespan(2500000);
    ss.setReceiveTimeout (timespan);
    try {
        for(;;)
        {
            array<char, 4096> buffer {'\0'};
            int n = ss.receiveBytes(buffer.data(), sizeof(buffer));
            //cout<<"Received "<<n<<" bytes"<<endl;
            cameras_XML.push_back(buffer.data());
        }
    }
    catch(const Poco::TimeoutException &ex)
    {
        cout<<"Timeout:"<<ex.what()<<endl;
    }
    cout<<cameras_XML.size()<<endl;
    ss.close();
    return cameras_XML;
}