boost::asio::io_service的使用详细步骤
时间: 2023-09-11 19:09:06 浏览: 121
boost_asio:如何使用 boost asio 编程
1. 引入boost库
```c++
#include <boost/asio.hpp>
```
2. 创建io_service对象
```c++
boost::asio::io_service io_service;
```
3. 创建socket对象
```c++
boost::asio::ip::tcp::socket socket(io_service);
```
4. 连接服务器
```c++
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 8080);
socket.connect(endpoint);
```
5. 发送数据
```c++
std::string message = "Hello, server!";
boost::system::error_code error;
boost::asio::write(socket, boost::asio::buffer(message), error);
if (error) {
std::cout << "Send failed: " << error.message() << std::endl;
}
```
6. 接收数据
```c++
char buf[1024];
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof) {
std::cout << "Connection closed by peer." << std::endl;
} else if (error) {
std::cout << "Receive failed: " << error.message() << std::endl;
} else {
std::cout << "Received " << len << " bytes: " << buf << std::endl;
}
```
7. 关闭socket
```c++
socket.close();
```
8. 运行io_service
```c++
io_service.run();
```
完整代码示例:
```c++
#include <iostream>
#include <boost/asio.hpp>
int main() {
boost::asio::io_service io_service;
boost::asio::ip::tcp::socket socket(io_service);
try {
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 8080);
socket.connect(endpoint);
std::string message = "Hello, server!";
boost::system::error_code error;
boost::asio::write(socket, boost::asio::buffer(message), error);
if (error) {
std::cout << "Send failed: " << error.message() << std::endl;
}
char buf[1024];
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof) {
std::cout << "Connection closed by peer." << std::endl;
} else if (error) {
std::cout << "Receive failed: " << error.message() << std::endl;
} else {
std::cout << "Received " << len << " bytes: " << buf << std::endl;
}
socket.close();
} catch (std::exception& e) {
std::cout << "Exception: " << e.what() << std::endl;
}
io_service.run();
return 0;
}
```
阅读全文