擅长:python、mysql、java
<p>使用<code>tcp::socket::read_some</code>方法。这个方法阻塞,直到有东西被接收到套接字,然后读取数据(而read(…)函数读取整个文件/套接字,直到EOF,只有在连接断开时才会发生)</p>
<p><a href="http://www.boost.org/doc/libs/1_64_0/doc/html/boost_asio/reference/basic_stream_socket/read_some/overload2.html" rel="nofollow noreferrer">You can read up the usage here.</a></p>
<p><strong>示例:</strong></p>
<pre><code>std::string recbuf;
while (true)
{
//write data
sock.write_some(buffer("ok", 2));
//read data
sock.read_some(buffer(recbuf, 1024), ec);
//handle error
if (ec && ec != error::eof) {
std::cout << "receive failed: " << ec.message() << std::endl;
}
else {
std::cout << recbuf << std::endl;
}
}
</code></pre>