boost::asio::read防止boost:asio::write向Java Socket发送数据

boost::asio::read prevents boost:asio::write from sending data to Java Socket

本文关键字:boost asio 数据 Socket write read 防止 Java      更新时间:2023-10-16

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

当我在boost::asio::write之后使用boost::asio::read等待服务器的响应时,服务器没有收到之前通过写发送的数据,客户端在读取时阻塞)。如果取消注释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服务器端:

连接通过套接字建立(来自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(),它也能工作,这真的很奇怪。

看起来代码本身工作得很好。

我已经在周围的软件之外尝试过了,所以它一定是软件内部的问题。