How to send an std::vector<unsigned char> using asio::UDP socket.send_to

断了今生、忘了曾经 提交于 2019-12-12 04:58:33

问题


I am trying to synchronously send an std::vector<unsigned char> through boost::asio::ip::udp from my server app to client app with following code like this:

boost::system::error_code ignored_error;
std::vector<unsigned char> buf_data;
std::size_t len = socket.send_to(boost::asio::buffer(buf_data), remote_endpoint, 0, ignored_error);

This causes a hang & socket.send_to never returns.

However, If I try to send a struct like below, it works nicely

struct MyStruct
{
    char name[1024];
    int age;
};

boost::system::error_code ignored_error;
MyStruct send_data = {"something", 123 };
std::size_t len = socket.send_to(boost::asio::buffer(&send_data, sizeof(send_data)), remote_endpoint, 0, ignored_error);

Also, If I try to send a std::string like below, it works as well.

What is different that I should do with call to socket.send_to when passing an std::vector<unsigned char> ? Does socket.send_to work with std::vector<unsigned char> or should use some other way to send the chars ?

PS: The size of vector I am trying to send is buf_data.size() is 140050 & I am on OSX


回答1:


If your buf_data contains at least one element, you can use the following:

boost::asio::buffer(&buf_data[0], buf_date.size())

as the first argument.



来源:https://stackoverflow.com/questions/43878810/how-to-send-an-stdvectorunsigned-char-using-asioudp-socket-send-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!