客户代码
#include <cstdlib>
#include <iostream>
#include <memory>
#include <utility>
#include <boost/asio.hpp>
#include <string>
#include <boost/array.hpp>
using namespace std;
using namespace boost::asio;
int main(int argc, char* argv[])
{
io_service service;
ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 2001);
ip::tcp::socket sock(service);
sock.connect(ep);
boost::asio::streambuf sb;
boost::system::error_code ec;
size_t len;
while (true)
{
//write data
sock.write_some(buffer("ok", 2));
//read data
read(sock, sb, transfer_all(),ec);
//handle error
if (ec && ec != error::eof) {
std::cout << "receive failed: " << ec.message() << std::endl;
}
else {
const char* data = buffer_cast<const char*>(sb.data());
std::cout << data << std::endl;
}
}
return 0;
}
服务器代码
^{pr2}$客户端可以向服务器发送“ok”,但不能从服务器接收“123”。在
如果我使用python编写的客户机,服务器和客户机可以很好地通信。在
有人能告诉我这个错误的原因吗?在
我发现了类似的问题boost::asio::ip::tcp::socket doesn't read anything。在
使用读直到可以解决这个问题。在
使用
tcp::socket::read_some
方法。这个方法阻塞,直到有东西被接收到套接字,然后读取数据(而read(…)函数读取整个文件/套接字,直到EOF,只有在连接断开时才会发生)You can read up the usage here.
示例:
相关问题 更多 >
编程相关推荐