I’m writing a client/server application in which, client is written in C++ and the server is Java. The communication between them is made by the UDP protocol.
They need to exchange string messages over the net.
Now, the communication works a lot, the client sends message and server receives it, but I noticed that the received string, on the Java side, is like trunked. I mean, if I try to display it onto the console, with the function:
System.out.println("This is the message received "
+ message + " by the client just now");
the result I obtain is:
This is the message received *message*
with the string “by the client just now” trunked out.
I think it’s due to some incompatibility between Java and C++, but I can’t found out the solution.
edit:
here’s the code of the receiver:
byte[] bytes = _packet.getData(); // Datagram Packet
hostName = getStringFromBytes(bytes, 0, 15);
(...)
private String getStringFromBytes (byte[] bytes, int lowerBound, int length)
{
byte[] bufferBytes = new byte[length];
System.arraycopy(bytes, lowerBound, bufferBytes, 0, length);
return new String(bufferBytes).trim();
}
and the sender:
if(sendto(_socket, buffer, BUFFER_LEN, 0, (struct sockaddr*) &_serverAddress, addressLenght) == -1)
cout << "Trasmission failed!\n" << endl;
where buffer is an array of char.
This line seems to indicate that buffer is a c-string. If this is the case, you need to parse out the extra NULL character on your server end. The NULL character from the c-string is probably causing the JAVA code to stop processing the string as soon as it sees the NULL character–which is what it should do.
You could probably just trim the last character off of the string in your JAVA code. Remember that C-strings always have an extra character at the end–a NULL character.
Also, is BUFFER_LEN a macro? What is it defined as? Try just sending the actual buffer length, instead of a predefined length.
i.e.
And in general, in C++ , when at all possible use std::string, not char*.