I'm using asio library (C++) and I would like to create a pair of server/client such that:
- The server is streaming data on some port;
- The client connect to that port and receive such data.
Now, in usual client/server applications the server is "listening" to some port, while the client connects to this port. In what I described above it seems that the part are switched, so I manage to write the following code for the server:
#include <iostream>
#include <numeric>
#include <vector>
#include "asio.hpp"
int main() {
constexpr int size = 10;
std::vector<int> vct(size);
std::iota(vct.begin(), vct.end(), 0);
asio::io_context context;
asio::ip::udp::resolver resolver{context};
asio::ip::udp::socket socket{context};
socket.open(asio::ip::udp::v4());
socket.connect(asio::ip::udp::endpoint(asio::ip::udp::v4(), 10888));
size_t len = socket.send(asio::buffer(vct));
std::cout << "Sent " << len << " b." << std::endl;
return EXIT_SUCCESS;
}
and the following for the client:
#include <iostream>
#include <vector>
#include "asio.hpp"
int main()
{
constexpr int size = 10;
std::vector<int> vct(size);
asio::io_context context;
asio::ip::udp::endpoint local_endpoint{asio::ip::address::from_string("127.0.0.1"), 10888};
asio::ip::udp::endpoint sender_endpoint;
asio::ip::udp::socket socket{context};
socket.open(asio::ip::udp::v4());
socket.bind(local_endpoint);
size_t len = socket.receive_from(asio::buffer(vct), sender_endpoint);
std::cout << "Received " << len << " b from " << sender_endpoint << std::endl;
for (auto i : vct)
std::cout << i << std::endl;
return EXIT_SUCCESS;
}
So I used connect
in the server while I use bind
in the client. This makes me a bit upset even if it seems to work.
My questions are
- Is this the correct way to setup a "streaming server" and a receiver (let us drop for the moment the issue about async, I mean here at the level of connection)
- Should
bind
andconnect
be used this way?