It seems that the code itself works fine. I have tried it outside the surrounding software - so it somehow has to be a problem within that software.
boost::asio::read prevents boost:asio::write from sending data to Java Socket
-
19-07-2023 - |
Вопрос
I'am trying to send data between a C++ application and a Java application back and forth. The C++ program is the client and the java program is the server. Sending the request from the client to the server works, but not the other way round.
When I use boost::asio::read
after boost::asio::write
to wait for the response of the server the data sent before via write is not received by the server and the client blocks at read). If I uncomment the boost::asio::read
command sending works.
Here are the important parts of the C++ client class:
Connection establishing:
_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);
First writing and then reading to socket:
// 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));
And on the Java server side:
Connection is established via Socket (Coming from ServerSocket.accept() ). Then a DataInputStream and a DataOutputStream is opened:
this.dis = new DataInputStream(socket.getInputStream());
this.dos = new DataOutputStream(socket.getOutputStream());
All the reading is bases on this method, the rest ist just conversion etc.:
private byte[] readBytes(int n) throws IOException {
byte[] data = new byte[n];
dis.readFully(data);
return data;
}
Do I do something wrong? It's really strange that it works without the boost::read().
Решение