在读取</tcp :: socket>之前关闭boost :: asio :: ssl :: stream <tcp :: socket>

时间:2015-03-17 05:52:11

标签: c++ sockets ssl boost

我正在尝试编写同步ssl客户端。这是我的代码:

class CHttpsSession
{
public:
    CHttpsSession(io_service& io_service, ssl::context &context, tcp::resolver::iterator endpoint_iterator) :
        m_socket(io_service, context)
    {
        error_code error = error::host_not_found;
        tcp::resolver::iterator end;
        while (error && endpoint_iterator != end)
        {
            m_socket.lowest_layer().close();
            m_socket.lowest_layer().connect(*endpoint_iterator++, error);
        }

        if (error)
        {
            throw system_error(error);
        }

        m_socket.handshake(ssl::stream_base::client);
    }

    void sendRequest(CHttpRequest& request)
    {
        write(m_socket, request.getRequest());
    }

    void receiveResponse(CHttpResponse& response)
    {
        streambuf reply;
        error_code error;
        read(m_socket, reply, transfer_all(), error); //here is error received
        if (error && error != error::eof)
            throw system_error(error);
        response.init(reply);
    }

private:
    ssl::stream<tcp::socket> m_socket;
}

int main(int argc, char* argv[])
{
    try
    {
        io_service io_service;
        string server = "some server here";
        string port = "some port here";
        tcp::resolver resolver(io_service);
        tcp::resolver::query query(std::string(server), std::to_string(port));
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        ssl::context ctx(io_service, ssl::context_base::sslv23_client);
        ctx.use_certificate_chain_file("path to certificate file");
        ctx.set_verify_mode(ssl::context_base::verify_none);
        auto session = new CHttpsSession(io_service, ctx, endpoint_iterator);

        CHttpRequest request;
        CHttpResonse response;
        //request initialization

        session.sendRequest(request);
        session.receiveResponse(response);
    }        
    catch (boost::system::system_error& exc)
    {
        cout<< exc.what() << std::endl;
    }
}

但是尝试从套接字读取数据时出现以下错误:不允许发送或接收数据的请求,因为套接字已经通过先前的关闭调用在该方向上关闭。

我也为非ssl客户端使用类似的代码,它可以工作。

我错过了什么吗?

更新

发现只有ssl流被关闭:底层的tcp套接字仍处于打开状态,数据可以通过它获得,但由于它是加密的,我无法使用它。

0 个答案:

没有答案