@Pigmon
2020-04-21T03:04:29.000000Z
字数 1810
阅读 1438
C++
官网的例子比较匪夷所思,我根据你的需求写了一个最简单的例子,你照着修改就可以发送不定长的json字符串了。
时间有限,我也是现学的,凑合看吧。注释写的很清楚了(我认为)。
endpoint 没查怎么翻译,我暂时理解为一种对一个端点的描述结构,所以翻译为 发送端描述 和 接收端描述。
本地收发,发送端口 8110,接收端口 8111。
#include <iostream>#include <string>#include <boost/asio.hpp>using boost::asio::ip::udp;// 这里弄个简单的不定长字符串数组循环发送int index = 0;std::string array_str[] = { "short", "little longer", "this is a much much longer string", "emmm..." };// 读取上面的不定长字符串数组,用来发给接收端std::string make_multi_size_string(){std::string ret = array_str[index++];if (index > 3) index = 0;return ret;}int main(){try{// 这句必须有,先别考虑原因boost::asio::io_context io_context;// 生成IP地址boost::asio::ip::address addr = boost::asio::ip::address::from_string("127.0.0.1");// 生成接收端描述 (IP, Port)udp::endpoint remote_endpoint(addr, 8111);// 建立 socket,第二个参数是发送端描述 (协议,发送端端口)udp::socket socket(io_context, udp::endpoint(udp::v4(), 8110));while (true){// 读取一个字符串std::string message = make_multi_size_string();// 核心操作:send_to ,把读取到的字符串发送给接收端size_t sentn = socket.send_to(boost::asio::buffer(message), remote_endpoint);std::cout << sentn << " Bytes sent.\n";Sleep(200);}}catch (std::exception& e){std::cerr << e.what() << std::endl;}return 0;}
#include <iostream>#include <boost/array.hpp>#include <boost/asio.hpp>using boost::asio::ip::udp;int main(int argc, char* argv[]){try{// 这句必须有,先别考虑原因boost::asio::io_context io_context;// 建立 socket,(协议,接收端口)udp::socket socket(io_context, udp::endpoint(udp::v4(), 8111));while (true){// 接收的缓存,如果是你的json应该申请为1024就够了吧。boost::array<char, 128> recv_buf;// 这是个输出参数,发送端描述,这里没啥用。// 但这个函数好像不存在没有这个参数的重载,所以只能写上。udp::endpoint sender_endpoint;// 核心操作:receive_from,将接受内容写入 recv_bufsize_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);// 根据接收数据长度截取字符串并输出,就是得到了最终的结果// 实际使用应该用string操作截取,这里我没时间弄了std::cout.write(recv_buf.data(), len);std::cout << std::endl;Sleep(200);}}catch (std::exception& e){std::cerr << e.what() << std::endl;}return 0;}