UDP 连接总是成功 [英] UDP Connect Always Succeeds

查看:25
本文介绍了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天全站免登陆