我编写了一个客户端,它在没有任何类的单个文件中连接到服务器。这显然不是一种好的编程方式,所以当代码最终按照我的意愿运行时,我使用以下 client.h 创建了 myclient 类:
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <string>
#include "mtbf.h"
#include <boost/date_time/posix_time/posix_time.hpp>
class myclient
{
public:
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver;
boost::asio::ip::tcp::socket sock;
boost::array<char, 4096> buffer;
typedef boost::posix_time::time_duration duration_t;
typedef boost::posix_time::ptime timestamp_t;
std::vector<std::string> tokens;
boost::system::error_code m_err_feedback;
enum ConnectionState
{
WAIT_FOR_HEADER,
WAIT_FOR_DATA,
PACKET_COMPLETE
};
myclient(std::string port);
private:
void read_handler(const boost::system::error_code &ec, std::size_t bytes_transferred);
void connect_handler(const boost::system::error_code &ec);
void resolve_handler(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it);
};
我没有写client.cpp的完整代码,但这里是错误发生的地方(构造函数)
myclient::myclient(std::string port):resolver(io_service),sock(io_service)
{
tcp::resolver::query query("127.0.0.1", port);
resolver.async_resolve(query, boost::bind(&myclient::resolve_handler, this));
io_service.run();
}
我对 c++ 相当陌生,但我知道我需要一个 boost::bind 来调用成员函数的引用
resolver.async_resolve(query, boost::bind(&myclient::resolve_handler, this));
但不知何故这不太正确..我收到一个错误:
error 8 error C2298: 'return': Invalid procedure for an expression with pointer to memberfunction C:\projekte\libs\boost_1_53_0-VC11\boost\bind\mem_fn.hpp 342 1 client
编辑:感谢您的回复..但似乎还有更多错误即将到来。我错过了一些微不足道的事情吗?这是来自 client.cpp 的代码(我删除了 read_handler 中的实际算法,因为它不重要)
#include "client.h"
using boost::asio::ip::tcp;
myclient::myclient(std::string port):resolver(io_service),sock(io_service)
{
tcp::resolver::query query("127.0.0.1", port);
resolver.async_resolve(query, boost::bind(&myclient::resolve_handler, this,boost::asio::placeholders::error,boost::asio::placeholders::iterator));
io_service.run();
}
void myclient::read_handler(const boost::system::error_code &ec, std::size_t bytes_transferred)
{
.
.
.
}
void myclient::connect_handler(const boost::system::error_code &ec)
{
if (!ec)
{
sock.async_read_some(boost::asio::buffer(buffer), boost::bind(&myclient::read_handler, this,&ec));
}
}
void myclient::resolve_handler(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it)
{
if (!ec)
{
sock.async_connect(*it, boost::bind(&myclient::connect_handler, this, &ec, it));
}
}
有了这个,我得到如下错误:
error 2 error C2825: "F": must be a class or namespace "::". C:\projekte\libs\boost_1_53_0-VC11\boost\bind\bind.hpp 69 1 client
error 3 error C2039: 'result_type': is not an element of '`global namespace'' C:\projekte\libs\boost_1_53_0-VC11\boost\bind\bind.hpp 69 1 client