I am trying to send some string from A Java client to a C server using C. First I send the length of the String. Then, I allocate the memory manually in C and finally I send the String character by character.
The problem that sometimes I get the right String and some times I get the whole String + Extra other unknown Character (like I am allocating more than I get).
Here is the Java Code:
protected void send(String data){
short dataLength=(short)data.length();
try {
out.write(dataLength);
for (int i=0; i<data.getBytes().length ;i++)
{
out.write(data.getBytes()[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And here is the C code :
void read4(int sock, int *data)
{
char dataRecv;
char* memoireAllouee=NULL;
int stringLength;
int i=0;
recv(sock, (char*)&dataRecv, sizeof(dataRecv), 0) ;
*data = dataRecv;
stringLength=dataRecv;
memoireAllouee=malloc(sizeof(char)*stringLength);
if (memoireAllouee==NULL)
{
exit(0);
}
for (i=0;i<stringLength;i++)
{
recv(sock, (char*)&dataRecv, sizeof(dataRecv), 0) ;
*data = dataRecv;
memoireAllouee[i]=dataRecv;
}
printf("\n\n%d\n\n\n",stringLength);
printf("\n%s\n",memoireAllouee);
}
If you think also that this method is not optimal can you help me with a faster one?
outis probably aDataOutputStream, and if so, the matching method iswrite( int )which writes the bottom 8 bits of theintto the stream. That explains why the length is being transmitted correctly (or close to it, it would have been much worse if it were really sending theshort). It also means that the conversion toshortis either completely unnecessary, or an attempt to save 16 bits of space in the temporary variable storing the length.