asio客户端心得

#pragma once

#include 
<boost/asio.hpp>
#include 
<boost/bind.hpp>
#include 
<boost/shared_ptr.hpp>
using boost::asio::ip::tcp;

class CAsioClient
{
public:
    CAsioClient(boost::asio::io_service
& io_service,tcp::endpoint& endpoint)
        : socket(io_service)
    {
        socket.async_connect(endpoint,
            boost::bind(
&CAsioClient::handle_connect,this,boost::asio::placeholders::error)
            );
        memset(getBuffer, 
0sizeof(getBuffer));
    }

    
virtual ~CAsioClient(void)
    {
        
if (sendBuffer != NULL)
        {
            delete sendBuffer;
        }
    }

private:
    
void handle_connect(const boost::system::error_code& error)
    {
        
if(!error)
        {
            sendBuffer 
= new BYTE[2];
            sendBuffer[
0= 0x68;
            sendBuffer[
1= 0x16;
            boost::asio::async_write(socket,boost::asio::buffer(sendBuffer, 
sizeof(sendBuffer)),
                boost::bind(
&CAsioClient::handle_write,this,boost::asio::placeholders::error));

            socket.async_read_some(boost::asio::buffer(getBuffer, 
sizeof(getBuffer)),
                boost::bind(
&CAsioClient::handle_read,this,boost::asio::placeholders::error)
                );

        }
        
else
        {
            socket.close();
        }
    }
    
void handle_read(const boost::system::error_code& error)
    {
        
if(!error)
        {
            socket.async_read_some(
                boost::asio::buffer(getBuffer, 
sizeof(getBuffer)),
                boost::bind(
&CAsioClient::handle_read,this,boost::asio::placeholders::error)
                );
        }
        
else
        {
            socket.close();
        }
    }

    
void handle_write(const boost::system::error_code& error)
    {
        
if (!error)
        {
            Sleep(
1000);
            sendBuffer 
= new BYTE[2];
            sendBuffer[
0= 0x68;
            sendBuffer[
1= 0x16;
            boost::asio::async_write(socket,boost::asio::buffer(sendBuffer, 
sizeof(sendBuffer)),
                boost::bind(
&CAsioClient::handle_write,this,boost::asio::placeholders::error));
        }
    }

private:
    tcp::socket socket;
    BYTE 
*sendBuffer;
    BYTE getBuffer[
1024];
};
posted @ 2011-07-04 18:03  kenter  阅读(1102)  评论(0编辑  收藏  举报