UDP连接始终成功 [英] UDP Connect Always Succeeds

查看:128
本文介绍了UDP连接始终成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Boost ASIO通过以太网通过以太网屏蔽连接到Arduino Nano.这是Arduino设置:

I am using Boost ASIO to connect to an Arduino Nano with an Ethernet Shield over ethernet. This is the Arduino setup:

#include <EtherCard.h>
ether.staticSetup("10.0.0.4", "10.0.0.1");
ether.udpServerListenOnPort(&callback_function, 1337);

这是我连接的C ++代码:

This is my C++ code that connects to it:

标题

#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>

boost::system::error_code error_1;
boost::shared_ptr <boost::asio::io_service> io_service_1;
boost::shared_ptr <boost::asio::ip::udp::socket> socket_1;

初始化

// 1. reset io service      
io_service_1.reset();
io_service_1 = boost::make_shared <boost::asio::io_service> ();

// 2. create endpoint
boost::asio::ip::udp::endpoint remote_endpoint(
    boost::asio::ip::address::from_string("10.0.0.4"), 
    1337
);

// 3. reset socket
socket_1.reset(new boost::asio::ip::udp::socket(*io_service_1));                

// 4. connect socket
socket_1->async_connect(remote_endpoint, socket_1_connect_callback);

// 5. start io_service_1 run thread after giving it work
boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));    

回调

function socket_1_connect_callback (const boost::system::error_code& error_1)
{
    // 1. check for errors
    if (error_1) 
    {
        std::cerr << "error_1.message() >> " << error_1.message().c_str() << std::endl;
        return;
    }
    else
    {
        INFO << "connection succeeded";
    }   

    return; 
}

即使Arduino没上电,插座也会每次连接.为什么连接不失败?

The socket connects every time, even if the Arduino is not powered. Why does it not fail to connect?

推荐答案

根据定义,UDP是无连接协议. 连接" UDP套接字只是一种简便的操作,它使您可以在不指定接收者的情况下在该套接字上发送数据报-它使用您提供给连接调用的数据报.

By definition, UDP is connection-less protocol. 'Connecting' a UDP socket is simply a convenience operation, which allows you to than send datagrams on that socket without specifying recipient - it uses the one you gave to a connect call.

但是除此之外,它什么也没做.除非您自己实现请求/响应方案,否则实际上没有任何方法可以检查是否有人在UDP的另一端进行监听.

But other than that, it does nothing. There is really no way to check if someone is listening on the other side of UDP, unless you implement a request/response scheme yourself.

您正在使用Boost.Asio的事实对此基本事实没有任何作用.

The fact that you are using Boost.Asio adds nothing to this basic fact.

这篇关于UDP连接始终成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆