Boost::asio: data get received only after other connection appeared
I'm trying to use code examples in my application. At a connection client sends "hello!" to the server. Server receives it and answers on it somehow (and ends message with "Hi, client! I'm server!") - but that's what i have: server doesn't receive anything until I connect to it by telnet and send something. After that it receives (prints) both clients and telnet messages.
Client:
socket.connect(tcp::endpoint(tcp::v4(), 21), error);
if (error)
throw boost::system::system_error(error);
boost::asio::write(socket, boost::asio::buffer("Hello!\n"), boost::asio::transfer_all(), ignored_error);
for (;;)
{
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
开发者_Python百科 break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
}
server:
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
for (;;)
{
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (buf[len-1] == '/n')
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::string a(buf.data());
}
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer("Hi, client! I'm server!"),
boost::asio::transfer_all(), ignored_error);
}
I'm afraid I forgot something to close (like socket). But anyway - and ideas?
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (buf[len-1] == '/n')
you've made some assumptions about tcp::ip::socket::read_some()
that are not true.
Remarks
The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.
I suggest you use the read()
free function as the documentation suggests.
精彩评论