简体   繁体   English

使用 Boost Asio c++ 打开和绑定 UDP 套接字的不同方法

[英]Different ways of opening and binding a UDP socket with Boost Asio c++

I'm trying to create a simple UDP broadcast class in c++ using the Boost Asio library.我正在尝试使用 Boost Asio 库在 C++ 中创建一个简单的 UDP 广播类。 Specifically, in the main class I'd like to instantiate a socket to both send and receive data.具体来说,在主类中,我想实例化一个套接字来发送和接收数据。 But I've seen three different ways of doing so, and I wanted to ask if anyone knew the difference?但是我已经看到了三种不同的方法,我想问是否有人知道其中的区别? These are the methods I've seen:这些是我见过的方法:

The first after creating the socket using a io_context, opens it:第一个使用 io_context 创建套接字后,打开它:

socket.open(udp::v4());

I've read somewhere that it works also in receiving after sending a packet, because calling socket.send(...) automatically binds the socket to a local endpoint (ie host address and a random port);我在某处读到它在发送数据包后也可以接收,因为调用socket.send(...)会自动将套接字绑定到本地端点(即主机地址和随机端口); but at this point anyone wanting to send a packet to this specific socket, how would be able to do so if the local endpoint is kind of "generated random" (the port is not known..).但是此时任何想要向该特定套接字发送数据包的人,如果本地端点是一种“生成的随机”(端口未知..),将如何做到这一点。

The second method I've seen is first opening the socket then binding it to a local endpoint:我见过的第二种方法是首先打开套接字,然后将其绑定到本地端点:

socket.open(udp::v4());
socket.bind(local_endpoint);

Finally the third method, consists of creating the socket with already a local endpoint, and use it without calling open():最后第三种方法,包括创建具有本地端点的套接字,并在不调用 open() 的情况下使用它:

udp::socket socket(io_context, local_endpoint);

So what would be the difference between the three, and would they all work?那么这三者之间有什么区别,它们都会起作用吗? What would be the best way?最好的方法是什么?

Thank you in advance!先感谢您!

The first method will create a socket without binding to a specific port.第一种方法将创建一个不绑定到特定端口的套接字。 This is fine if you don't care about someone initiating the messages with you.如果您不关心有人向您发送消息,这很好。 IE: You send a message to a recipent, they can reply back because they received the sender's IP and Port along with the message. IE:您向recipent发送消息,他们可以回复,因为他们收到了发件人的IP和Port以及消息。

If you want someone to be able to message you on a specific IP and port, you can initialize your socket like so:如果您希望某人能够在特定 IP 和端口上向您发送消息,您可以像这样初始化您的套接字:

socket_(io_service, udp::endpoint(udp::v4(), port))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM