问题
I am currently working on a client server TCP/IP application using Boost ASIO. The client sends data to the server using the following statement
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer("Hello World\0"), ignored_error);
The server reads this data as such (from an Asynch. read)
boost::asio::async_read(*sock, boost::asio::buffer(buf_server),boost::bind(&ServerRead,boost::asio::placeholders::error));
Here is where the reading is done
boost::array<char, 158> buf_server;
void ServerRead(const boost::system::error_code& error)
{
if(!error)
{
std::cout << "Message: " << buf_server.data() << std::endl;
}
else
{
std::cout << "Error occurred." << error.message() << std::endl;
}
}
However I get the error "End of file". So now I have two questions
How can I resolve this issue. What am i doing wrong here ?
Suppose my
buf_server
was only 5 characters instead of 158. How could I make my receiver use this buffer only to read the entire data andstd::cout
it?
回答1:
This behavior should be expected when you instruct an application to read 158 bytes but only 12 are sent. To resolve this you can send a fixed size header indicating the message size, the chat client and server example included in the Asio documentation shows how to accomplish this, an excerpt from the client example:
void handle_connect(const boost::system::error_code& error)
{
if (!error)
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(&chat_client::handle_read_header, this,
boost::asio::placeholders::error));
}
}
void handle_read_header(const boost::system::error_code& error)
{
if (!error && read_msg_.decode_header())
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
boost::bind(&chat_client::handle_read_body, this,
boost::asio::placeholders::error));
}
else
{
do_close();
}
}
void handle_read_body(const boost::system::error_code& error)
{
if (!error)
{
std::cout.write(read_msg_.body(), read_msg_.body_length());
std::cout << "\n";
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(&chat_client::handle_read_header, this,
boost::asio::placeholders::error));
}
else
{
do_close();
}
}
Alternatively, or use a more exotic protocol such as HTTP where you read until encountering a \r\n
delimiter.
来源:https://stackoverflow.com/questions/15558223/exception-while-receiving-data-from-client-end-of-file-error