I am trying to send some string from a Java client to server C using C. First I send the length of the string. Then I manually allocate the memory in C and finally I send the String character to the character.
The problem is that sometimes I get the correct string, and sometimes I get the whole String + Extra another unknown character (for example, I allocate 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) {
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 this method is not optimal, can you help me faster?
source
share