Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost asio - udp server

I saw the official async udp server example from boost doc. There you create a single udp socket, bind it to a local port and do something like this:

socket(ioService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port))

socket.async_receive_from(buffer(data, max_length), senderEndpoint, boost::bind(&Request::HandleReceiveFrom, this,
    boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));

How can I handle multiple concurrent udp connections from clients, because if I try to create another socket using

socket(ioService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port))

i get bind errors because I already have a socket bound to the same port.

EDIT I can send clients back responses using a different server source port but they will not recognize the response even though I sent the response back to the same client ip/client destination port.

like image 709
Ghita Avatar asked Mar 09 '26 02:03

Ghita


2 Answers

UDP is a connectionless transport so the concept of connections is meaningless as far as UDP is concerned.

If you want to send data back to the originator of the message you'll need to keep a copy of the sender_endpoint returned in the async_receive_from callback and pass it back in the async_send_to.

This also assumes that the client is also polling/reading and expecting a reply. It need not listen on the same bound port as the server (you don't need to bind with UDP on the client side).

I recommend you have a read of Beej's guide to network programming to help you understand what's going on under the hood of boost ASIO. Boost ASIO complicates things a lot IMHO.

http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#sendtorecv

like image 167
hookenz Avatar answered Mar 11 '26 16:03

hookenz


If your clients send their messages to the same port on your server then the only way to distinguish them is by the remote port or a combination of remote port and remote ip.

You create some sort of mapping from client-id (e.g. pair<remote_ip, remote_port>) to a dispatcher type (e.g map< pair<remote_ip, remote_port>, dispatcher>). This then it's up to you to make it threaded in order to support concurrent requests.

like image 45
StackedCrooked Avatar answered Mar 11 '26 15:03

StackedCrooked



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!