boost :: asio :: read阻止boost:asio :: write从发送数据到Java Socket

时间:2014-05-10 12:39:26

标签: java c++ sockets boost boost-asio

我正在尝试在C ++应用程序和Java应用程序之间来回发送数据。 C ++程序是客户端,java程序是服务器。将请求从客户端发送到服务器可以正常工作,但不是相反。

当我在boost::asio::read之后使用boost::asio::write等待服务器的响应时,服务器不会接收通过写入之前发送的数据,并且客户端会在读取时阻止)。如果我取消注释发送工作的boost::asio::read命令。

以下是C ++客户端类的重要部分:

连接建立:

_socket = new tcp::socket(_io_service);
tcp::no_delay option(true);
tcp::resolver resolver(_io_service);
boost::asio::connect(*_socket, resolver.resolve({_host, _port}));
_socket->set_option(option);

首先写入然后读取到套接字:

// Send length of the query
uint32_t length = message.size();
boost::asio::write(*_socket, boost::asio::buffer(&length, 4));

// Now send the message
const char *messageBuffer = message.c_str();
size_t messageBufferLength = std::strlen(messageBuffer);
boost::asio::write(*_socket, boost::asio::buffer(messageBuffer, messageBufferLength));

// Receive length of answer
uint32_t lengthAnswer = 0;
boost::asio::read(*_socket, boost::asio::buffer(&lengthAnswer, 4));

在Java服务器端:

通过Socket建立连接(来自ServerSocket.accept())。然后打开DataInputStream和DataOutputStream:

this.dis = new DataInputStream(socket.getInputStream());
this.dos = new DataOutputStream(socket.getOutputStream());

所有阅读都是基于这种方法,其余的只是转换等:

private byte[] readBytes(int n) throws IOException {
    byte[] data = new byte[n];
    dis.readFully(data);
    return data;
}

我做错了吗?如果没有boost :: read(),它真的很奇怪。

1 个答案:

答案 0 :(得分:0)

似乎代码本身工作正常。我在周围的软件之外尝试过它 - 所以它在某种程度上必须是该软件中的一个问题。