同步模式下的结构体传输与原生套接字实现方式完全一致,读者需要注意的是在接收参数是应该使用socket.read_some
函数读取,发送参数则使用socket.write_some
函数实现,对于套接字的解析同样使用强制指针转换的方法。
服务端代码如下所示
#include <iostream> #include <boost/asio.hpp>
typedef struct { int uuid; char uname[1024]; }message;
using namespace boost::asio;
int main(int argc, char* argv[]) { io_service io_service; ip::tcp::acceptor acceptor(io_service,ip::tcp::endpoint(ip::tcp::v4(), 1000)); ip::tcp::socket socket(io_service);
acceptor.accept(socket);
boost::system::error_code error_code;
char recv_buffer[sizeof(message) * 2] = { 0 }; socket.read_some(boost::asio::buffer(recv_buffer, sizeof(message) * 2), error_code); message *msg = (message *)recv_buffer;
std::cout << "数组1: " << msg[0].uname << std::endl; std::cout << "数组2: " << msg[1].uname << std::endl;
if (error_code) { std::cout << boost::system::system_error(error_code).what() << std::endl; return -1; }
std::system("pause"); return 0; }
|
客户端代码如下所示
#include <iostream> #include <boost/asio.hpp>
using namespace boost::asio;
typedef struct { int uuid; char uname[1024]; }message;
message msg[2];
int main(int argc, char* argv[]) { io_service io_service; ip::tcp::socket socket(io_service); ip::tcp::endpoint ep(ip::address_v4::from_string("127.0.0.1"), 1000);
boost::system::error_code error_code; socket.connect(ep, error_code);
char send_buffer[sizeof(message) * 2] = { 0 };
msg[0].uuid = 100; strcpy(msg[0].uname, "lyshark");
msg[1].uuid = 200; strcpy(msg[1].uname, "admin");
memcpy(send_buffer, &msg, sizeof(message) * 2); socket.write_some(boost::asio::buffer(send_buffer, sizeof(message) *2 ));
if (error_code) { std::cout << boost::system::system_error(error_code).what() << std::endl; return -1; }
std::system("pause"); return 0; }
|
读者可自行编译并运行上述代码,则可实现对结构体的传输功能,输出效果如下图所示;