connect on “connection less” boost::asio::ip::udp:

2020-03-19 01:47发布

问题:

I've been learning about UDP socket lately by browsing the net and all the pages that were explaining it were mentioning that UDP sockets are "connection less". This, if I understand it correctly means that one does not have a "connection" between two sockets but instead shoots datagram packets to specified endpoints without knowing whether the other end is listening.

Then I go and start reading the boost::asio::ip::udp::socket docs and find that it mentions API like:

  • async_connect: Start an asynchronous connect.
  • async_receive: Start an asynchronous receive on a connected socket.
  • async_send: Start an asynchronous send on a connected socket.

Now this is a bit confusing for a novice. I can find 3 possible causes for my confusion (in order of likehood :) )

  1. I'm missing something
  2. The asio implementation is doing something behind the scenes to virtualize the connection.
  3. The documentation is wrong

There is also a slight glitch in the docs, when you open the page for basic_datagram_socket::async_connect the example in there is instantiating TCP sockets (instead of UDP ones).

Would someone please enlighten me?

回答1:

The Single UNIX specification has a better explanation of what connect does for connection-less sockets:

If the initiating socket is not connection-mode, then connect() sets the socket's peer address, but no connection is made. For SOCK_DGRAM sockets, the peer address identifies where all datagrams are sent on subsequent send() calls, and limits the remote sender for subsequent recv() calls.