Sending string from Java to C (Socket)

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) {
        // 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 this method is not optimal, can you help me faster?

+3
source share
2 answers

To answer the second question:

for (int i=0; i<data.getBytes().length ;i++)
{
    out.write(data.getBytes()[i]);
}

should be simple:

out.write(data.getBytes());

and

for (i=0;i<stringLength;i++)
{
    recv(sock, (char*)&dataRecv, sizeof(dataRecv), 0) ;
    *data = dataRecv;
    memoireAllouee[i]=dataRecv;
}

it should be:

int offset= 0;
while (offset < stringLength)
{
    int count = recv(sock, &memoireAllouee[offset], stringLength-offset 0) ;
    if (count == 0)
        // premature EOS .. do something
        break;
    if (count == -1)
        // Error ... do something
        break;
    offset += count;
}
+4
source
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();
    }       
}

-, getBytes() . byte[] byteArray - . , out.write(byteArray), for?

-, data.length() data.getBytes().length(). , byteArray.length data.length().

, , . Charset, , Charset , .

+9

All Articles