简体   繁体   中英

Boost.Asio datagram (UDP) socket that is both bound and connected

I have problems understanding the concept behind Boost.Asio's (using v1.49.0) boost::asio::ip::udp::socket sockets.

First I am gonna to to explain what I want to achieve:

  • I hide the Boost.Asio sockets behind a very simple interface ( Pure Abstract Base Class ), so I have two wrapper classes that allow to access either a stream socket or a datagram socket.
  • I want to configure both the local endpoint and the remote endpoint before passing the Boost.Asio socket to the constructor of my wrapper class.
  • I want to use the socket.receive (alternatively boost::asio::read ) and socket.send (alternatively boost::asio::write ) member functions instead of the socket.receive_from and socket.send_to member functions.
  • The only way to use socket.send and socket.receive with a boost::asio::ip::udp::socket seems to connect the socket.

A UDP socket can both be bound and connected:

The problem is, that even though I am able to

  1. Open the socket,
  2. Set socket options,
  3. Bind the socket,
  4. Connect the socket,

and to be able to send data via the socket, I can not receive data from the socket. If I don't connect the socket, I can receive data via the bound local endpoint, but I am unable to send data with the approached described.

  1. So my central question is: Am I trying something that is impossible to achieve?
  2. Can I only use bind or connect with one socket instance?
  3. If the answer to the two previous questions is no: What do I have to do, to be able to receive and send data via a bound and connected Boost.Asio UDP socket.

I know that UDP is in fact connectionless, therefore the text uses Boost.Asio terminology. I have also read connect on "connection less" boost::asio::ip::udp::socket which seems to indicate that it is impossible what I am trying.

You are missing one point from man page of connect :

If the socket sockfd is of type SOCK_DGRAM, then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received .

This means, that if you want to connect the socket, then it will be able to receive datagrams only from remote endpoint (the connected one), ie peer will have to bind own socket before sending datagram to your socket waiting for data.

If you need to received data from more than one peer, you can connect udp socket to "any" address (ie 0.0.0.0 - udp::v4()) and some port.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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