Boost 库为 TCP 客户端和服务器提供了可靠、高效的通信支持。反射则是一种通过动态语言机制实现程序运行时自我修改的技术。在 C++ 中,可以使用模板特化等技巧实现类似的反射机制。
cpp
#include <iostream>
#include <boost/asio.hpp>
class TcpClient {
public:
TcpClient(const std::string& address, uint16_t port)
: m_server_address(address),
m_server_port(port),
m_socket(m_io_context),
m_strand(m_io_context)
{
// Connect to the server
boost::asio::ip::tcp::resolver resolver(m_io_context);
boost::asio::ip::tcp::resolver::results_type endpoints
= resolver.resolve(address, std::to_string(port));
boost::asio::async_connect(m_socket, endpoints,
[this](const boost::system::error_code& error, const boost::asio::ip::tcp::endpoint& /*endpoint*/)
{
if (!error) {
doRead();
} else {
std::cerr << error.message() << std::endl;
}
});
// Run the I/O service in a separate thread
m_thread = std::thread([this]() { m_io_context.run(); });
}
~TcpClient() {
m_io_context.stop();
if (m_thread.joinable()) {
m_thread.join();
}
}
// Send data to the server
void send(const std::string& data) {
boost::asio::post(m_strand, [this, data]() {
// Ensure that the buffer stays valid until the write operation completes
auto buffer = std::make_shared<std::string>(data);
boost::asio::async_write(m_socket, boost::asio::buffer(*buffer),
[buffer](const boost::system::error_code& error, std::size_t /*bytes_transferred*/) {
if (error) {
std::cerr << error.message() << std::endl;
}
});
});
}
// Set the callback function to be called when data is received from the server.
template<class Callback>
void setDataReceivedCallback(Callback callback) {
m_data_received_callback = std::move(callback);
}
private:
// Start an asynchronous read operation to receive data from the server
void doRead() {
auto buffer = std::make_shared<boost::asio::streambuf>();
boost::asio::async_read_until(m_socket, *buffer, '\n',
[this, buffer](const boost::system::error_code& error, std::size_t bytes_transferred) {
if (!error) {
// Call the callback function with the received data
std::istream input(buffer.get());
std::string line;
std::getline(input, line);
m_data_received_callback(line);
doRead();
} else {
std::cerr << error.message() << std::endl;
}
});
}
std::string m_server_address;
uint16_t m_server_port;
boost::asio::io_context m_io_context;
boost::asio::ip::tcp::socket m_socket;
boost::asio::io_context::strand m_strand;
std::thread m_thread;
std::function<void(const std::string&)> m_data_received_callback;
};
// Specialization of onDataReceived for std::string
template <>
void TcpClient::setDataReceivedCallback(std::function<void(const std::string&)> callback) {
m_data_received_callback = std::move(callback);
}
// Example usage
void onDataReceived(const std::string& data) {
std::cout << "Received data: " << data << std::endl;
}
int main() {
TcpClient client("127.0.0.1", 12345);
client.setDataReceivedCallback(onDataReceived);
client.send("Hello, world!\n");
return 0;
}