class proxy : public boost::enable_shared_from_this<proxy> {
proxy(ip::tcp::endpoint ep_client, ip::tcp::endpoint ep_
server) : ... {}
public:
static ptr start(ip::tcp::endpoint ep_client,
ip::tcp::endpoint ep_svr) {
ptr new_(new proxy(ep_client, ep_svr));
// … 连接到两个端
return new_;
}
void stop() {
// ... 关闭两个连接
}
bool started() { return started_ == 2; }
private:
void on_connect(const error_code & err) {
if ( !err) {
if ( ++started_ == 2) on_start();
} else stop();
}
void on_start() {
do_read(client_, buff_client_);
do_read(server_, buff_server_);
}
... private:
ip::tcp::socket client_, server_;
enum { max_msg = 1024 };
char buff_client_[max_msg], buff_server_[max_msg];
int started_;
};
class proxy : public boost::enable_shared_from_this<proxy> {
...
void on_read(ip::tcp::socket & sock, const error_code& err, size_t
bytes) {
char * buff = &sock == &client_ ? buff_client_ : buff_server_;
do_write(&sock == &client_ ? server_ : client_, buff, bytes);
}
void on_write(ip::tcp::socket & sock, const error_code &err,
size_t bytes){
if ( &sock == &client_) do_read(server_, buff_server_);
else do_read(client_, buff_client_);
}
void do_read(ip::tcp::socket & sock, char* buff) {
async_read(sock, buffer(buff, max_msg),
MEM_FN3(read_complete,ref(sock),_1,_2),
MEM_FN3(on_read,ref(sock),_1,_2));
}
void do_write(ip::tcp::socket & sock, char * buff, size_t size) {
sock.async_write_some(buffer(buff,size),
MEM_FN3(on_write,ref(sock),_1,_2));
}
size_t read_complete(ip::tcp::socket & sock,
const error_code & err, size_t bytes) {
if ( sock.available() > 0) return sock.available();
return bytes > 0 ? 0 : 1;
}
};
int main(int argc, char* argv[]) {
ip::tcp::endpoint ep_c( ip::address::from_string("127.0.0.1"),
8001);
ip::tcp::endpoint ep_s( ip::address::from_string("127.0.0.1"),
8002);
proxy::start(ep_c, ep_s);
service.run();
}
原文地址:http://blog.csdn.net/mmoaay/article/details/41208407