zoukankan      html  css  js  c++  java
  • 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];
    };
  • 相关阅读:
    7.15 更改累计和中的值
    7.10 计算中间值
    7.11 求总和的百分比
    7.9 计算模式
    7.8 计算累计差
    7.4 求一个表的行数
    7.6 生成累计和
    7.7 生成累积乘积
    7.2 求某列中的最小、最大值
    7.3 对某列的值求和
  • 原文地址:https://www.cnblogs.com/kenter/p/2097647.html
Copyright © 2011-2022 走看看