套接字不能接收数据?客户端是用助推器图书馆。服务器是用python编写的

2024-03-29 12:30:53 发布

您现在位置:Python中文网/ 问答频道 /正文

客户代码

#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编写的客户机,服务器和客户机可以很好地通信。在

有人能告诉我这个错误的原因吗?在


Tags: 代码ip服务器dataincludeserviceerrorsb
2条回答

我发现了类似的问题boost::asio::ip::tcp::socket doesn't read anything。在

使用读直到可以解决这个问题。在

使用tcp::socket::read_some方法。这个方法阻塞,直到有东西被接收到套接字,然后读取数据(而read(…)函数读取整个文件/套接字,直到EOF,只有在连接断开时才会发生)

You can read up the usage here.

示例:

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;
    }
}

相关问题 更多 >