上代码,非常简单,使用参数控制发送和接收
#define _CRT_SECURE_NO_WARNINGS
#include
// 3rd party includes.
#include
#include
#include
using namespace std;
using namespace asio::ip;
void read(asio::ip::udp::socket& socket)
{
asio::ip::udp::endpoint sender;
std::vector buffer;
std::size_t bytes_readable = 0;
for (;;)
{
// Poll until data is available.
while (!bytes_readable)
{
// Issue command to socket to get number of bytes readable.
asio::socket_base::bytes_readable num_of_bytes_readable(true);
socket.io_control(num_of_bytes_readable);
// Get the value from the command.
bytes_readable = num_of_bytes_readable.get();
// If there is no data available, then sleep.
if (!bytes_readable)
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
//boost::this_thread::sleep(boost::posix_time::seconds(1));
}
}
// Resize the buffer to store all available data.
buffer.resize(bytes_readable);
// Read available data.
socket.receive_from(
asio::buffer(buffer, bytes_readable),
sender);
// Extract data from the buffer.
std::string message(buffer.begin(), buffer.end());
// Output data.
std::cout
关注
打赏