user2212461
user2212461

Reputation: 3253

How to send java byte[] on tcp socket to c++ char[] on server?

I want to send a byte[] array from a java client to a server that receives the data in C++. The byte array contains characters and integers that are converted to bytes (its a wave header). The server doesn't receive the values correctly. How can I send the byte[] so that the server socket can write it to a char[]? I am using the following code:

Client.java:

//Some example values in byte[]
byte[] bA = new byte[44];
bA[0]='R';
...
bA[4]=(byte)(2048 & 0xff);
...
bA[16] = 16;
....

//Write byte[] on socket
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(bA,0,44);

Server.cpp

int k = 0,n = 0;
char buffer[100];
ofstream wav("out.wav", ios::out | ios::binary);
while(k<44){//receive 44 values
    memset(buffer ,0 , 100);
    n = recv(sock , buffer , 100 , 0);
    k += n;
    buffer[99] = '\0';
    wav.write(buffer,n);
}

Upvotes: 0

Views: 1559

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

One issue I see is if you receive 100 characters, you're corrupting the data with this line:

buffer[99] = '\0';

If there is a character other than NULL at that position, you've corrupted the data. Since the data is binary, there is no need to null terminate the buffer. Remove that line from your loop.

Instead, rely on the return value of recv to determine the number of characters to copy to the stream. Which brings up another point -- you're not checking if recv returns an error.

Upvotes: 2

Related Questions