基于boost1.60,写一个tcp通信的客户端
时间: 2024-03-11 10:49:49 浏览: 99
以下是基于boost1.60写的一个简单的TCP客户端示例代码。请注意,这只是一个示例,您需要根据您的具体需求进行修改和调整。
```c++
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: tcp_client <host> <port>\n";
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], argv[2]);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
std::cout << "Connected to " << argv[1] << ":" << argv[2] << std::endl;
// 发送消息
std::string message = "Hello, world!";
boost::asio::write(socket, boost::asio::buffer(message));
// 接收响应
boost::asio::streambuf receive_buffer;
boost::asio::read(socket, receive_buffer, boost::asio::transfer_all());
// 处理响应
std::string response = boost::asio::buffer_cast<const char*>(receive_buffer.data());
std::cout << "Received response: " << response << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
```
使用时,您需要将`<host>`和`<port>`替换为您要连接的服务器的主机名和端口号。如果需要,您还需要根据您的实际情况修改发送和接收的消息。
阅读全文