本文以一段示例代码,说明使用boost asio进行同步通讯的使用方法。
#include <iostream> #include <boost/asio.hpp> using namespace std; using boost::asio::ip::tcp; int main() { boost::asio::io_service ioservice; // I/O事件模型封装,如win下的iocp,unix下的poll, linux下的epoll等 tcp::socket socket(ioservice); tcp::endpoint endpoint; // tcp端点,包含地址和端口 boost::system::error_code errcode; tcp::resolver resolver(ioservice); // 地址名称解析器 tcp::resolver::iterator iter_endpoint; // resolver一次可返回多个地址,使用迭代器逐个访问 tcp::resolver::query query("mail.163.com", "pop3"); // 主机地址查询条件类,第一个参数是主机名,后一个是所需连接的服务名。 // 指定服务名可以使返回的endpoint除了包含主机地址,还会设定该服务的默认端口(如pop3默认端口为110) // 如果只需要查询主机地址,则服务名可以为空字符串(返回的endpoint.port()==0) iter_endpoint = resolver.resolve(query, errcode); // 解析所需的服务地址 if ( errcode.value() != 0) { cout<<"error code: "<<errcode.value()<<", "<<"error message: "<<errcode.message()<<endl; return 1; } // 获取找到的目标服务端点地址和端口(存储在endpoint实例中) endpoint = iter_endpoint->endpoint(); cout<<endpoint.address()<<":"<<endpoint.port()<<endl; // pop3命令 const char *cmd_user = "user myuser\n"; const char *cmd_pass = "pass mypass\n"; const char *cmd_list = "list\n"; const char *cmd_quit = "quit\n"; char result[256]; // 服务器返回消息缓存 try { // 连接POP3服务器,并获取服务器欢迎消息。 // boost::asio::buffer函数将创建一个缓存包装对象,内部地址指向result变量 socket.connect(endpoint); size_t len = socket.read_some(boost::asio::buffer(result, 256)); if ( len > 0 ) { result[len] = ‘\0‘; cout<<"received: "<<result<<endl; } // 发送用户命令, 并接收回复 socket.send(boost::asio::buffer(cmd_user, strlen(cmd_user))); len = socket.read_some(boost::asio::buffer(result, 256)); if ( len > 0 ) { result[len] = ‘\0‘; cout<<"received: "<<result<<endl; } // 发送口令命令, 并接收回复 socket.send(boost::asio::buffer(cmd_pass, strlen(cmd_pass))); len = socket.read_some(boost::asio::buffer(result, 256)); if ( len > 0 ) { result[len] = ‘\0‘; cout<<"received: "<<result<<endl; } // 发送退出命令, 并接收回复 socket.send(boost::asio::buffer(cmd_quit, strlen(cmd_quit))); len = socket.read_some(boost::asio::buffer(result, 256)); if ( len > 0 ) { result[len] = ‘\0‘; cout<<"received: "<<result<<endl; } socket.close(); } catch (const boost::system::system_error& e) { cout<<"connect error: "<<e.what()<<endl; } return 0; }
时间: 2024-10-10 13:53:57