简体   繁体   中英

boost::asio read/write trouble

I started to learn the boost::asio and tried to make simple client-server application. At now I have troubles with server. Here it code:

int main(int argc, char* argv[])
{
    using namespace boost::asio;

    io_service service;
    ip::tcp::endpoint endp(ip::tcp::v4(), 2001);
    ip::tcp::acceptor acc(service, endp);

    for (;;)
    {
        socker_ptr sock(new ip::tcp::socket(service));
        acc.accept(*sock);
        for (;;)
        {
            byte data[512];

            size_t len = sock->read_some(buffer(data));  // <--- here exception at second iteration

            if (len > 0)
                write(*sock, buffer("ok", 2));
        }
    }
}

It correctly accepted the client socket, correctly read, then it write data and strarted new iteration. On second iteration throwed exception. It looks like: 在此处输入图片说明 And I don`t get why it happens? I just need that server must read/write continuosly while the client present. And when the client gone the server must accept next client.

So the main question: why excpection happens and what how to aviod it?

...

UPDATE1: I found that at first iteration the error code of both read/write operation is successful. But (!) on second iteration at place where exception reised the error code is "End of file". But why?

You get the end of file condition because the remote end of the connection closed or dropped the connection.

You should be handling the system errors, or using the overloads that take a reference to boost::system::error_code . How else would you ever terminate the infinite loop?

Live On Coliru

#include <boost/asio.hpp>
#include <iostream>

int main()
{
    using namespace boost::asio;

    io_service service;
    ip::tcp::endpoint endp(ip::tcp::v4(), 2001);
    ip::tcp::acceptor acc(service, endp);

    for (;;)
    {
        ip::tcp::socket sock(service);
        acc.accept(sock);
        boost::system::error_code ec;

        while (!ec)
        {
            uint8_t data[512];

            size_t len = sock.read_some(buffer(data), ec);

            if (len > 0)
            {
                std::cout << "received " << len << " bytes\n";
                write(sock, buffer("ok", 2));
            }
        }

        std::cout << "Closed: " << ec.message() << "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM