Lai Yu-Hsuan
Lai Yu-Hsuan

Reputation: 28071

How can TCP socket know it has read all thing?

There is a very simple socket server implemented by boost::asio.

tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
tcp::socket(io_service) sock;
a.accept(sock);
char data[1024];
boost::system::error_code error;
size_t length = sock->read_some(boost::asio::buffer(data), error);
std::cout << "Got: " << data << std::endl;

And its client looks like:

size_t request_length = strlen(request);
boost::asio::write(s, boost::asio::buffer(request, request_length));

(Both got from the official examples)

When I sent hello, world! to the socket, I got Got: hello, world! immediately. But its buffer has 1024 bytes. How could it know when to finish reading?

EDIT:

Sorry for my poor description. My question is how read_some() know when it should return.

Upvotes: 1

Views: 1632

Answers (1)

Dave Rager
Dave Rager

Reputation: 8150

read_some() will return when it reads at least one byte from the receive buffer. If there is data in the receive buffer it will try to read as much as it can up to a specified size. It may or may not read the entire message during a single read.

In your case you seem to get the entire message by chance. read_some() could very well have only read a single byte. You would be better to call read_some() from within a loop incrementing the start index of your buffer by the length of the previous read.

Something like:

size_t length = 0;
while(length < MESSAGE_LENGTH)
{
    length += sock->read_some(boost::asio::buffer(&data[lenth], 1024 - length), error);
}

This is of course simplified for illustration. You should also take care of error conditions and such. But this should be enough to get you started.

Upvotes: 7

Related Questions