请用C++ 的 boost.asio 库实现一个简单示例
时间: 2024-05-10 14:20:41 浏览: 120
以下是一个简单的示例,使用boost.asio库实现了一个基于TCP协议的echo服务器和客户端。当客户端向服务器发送消息时,服务器将原封不动地返回该消息。
服务器端代码:
```
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main()
{
try
{
boost::asio::io_service io_service;
//监听端口号为1234
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 1234));
while (true)
{
tcp::socket socket(io_service);
//等待客户端连接
acceptor.accept(socket);
boost::system::error_code error;
//读取客户端发送的消息
boost::asio::streambuf buffer;
boost::asio::read_until(socket, buffer, "\n", error);
if (error)
std::cerr << "Error reading: " << error.message() << std::endl;
else
{
std::string message = boost::asio::buffer_cast<const char*>(buffer.data());
std::cout << "Received message: " << message;
//将消息原封不动地返回
boost::asio::write(socket, boost::asio::buffer(message), error);
if (error)
std::cerr << "Error writing: " << error.message() << std::endl;
}
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
```
客户端代码:
```
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main()
{
try
{
boost::asio::io_service io_service;
//连接服务器端口号为1234
tcp::resolver resolver(io_service);
tcp::resolver::query query("localhost", "1234");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
std::string message;
std::cout << "Enter message: ";
std::getline(std::cin, message);
//向服务器发送消息
boost::asio::write(socket, boost::asio::buffer(message + "\n"));
//读取服务器返回的消息
boost::asio::streambuf buffer;
boost::asio::read_until(socket, buffer, "\n");
std::string response = boost::asio::buffer_cast<const char*>(buffer.data());
std::cout << "Received response: " << response;
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
```
阅读全文