I am trying to build a simple connection between my Java server (it sends information) and my C client (it receives info).
I want to send one single integer representing the size of an array and then a byte array itself. My java code looks like this
Socket sc = new Socket("52.187.54.73", 19000);
while(true)
{
System.out.println("Socket open");
DataOutputStream outToClient = new DataOutputStream(sc.getOutputStream());
Random rand = new Random();
int rlen = rand.nextInt(10)%10 + 1;
byte[] a = new byte[rlen];
System.out.println("Size of the array is " + rlen);
for(int i = 0; i < rlen; i++)
a[i] = (byte)rand.nextInt(100);
outToClient.write(rlen);
outToClient.write(a,0,rlen);
//close socket
sc.close();
System.out.println("Done!");
//Break once done
break;
}
and my C code looks like this
ptr1 = (void *)calloc(1, sizeof(int));
while(1){
sin_size = sizeof(client_addr);
connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);
printf("\n Got a connection from (%s ,%d)",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
bytes_received = recv(connected,ptr1,10,0);
if(bytes_received<0){
printf("Something went wrong %s\n", strerror(errno));
}
printf("Bytes received: %d \n", bytes_received);
for(int i =0; i<bytes_received; i++){
unsigned char a = *(unsigned char *)(ptr1 + i*sizeof(unsigned char));
printf("Inc: %d", a);
}
Assuming that the above block of code works and I am able to get the value of rlen
the code for processing the array is as follows:
ptr2 = calloc(rlen, sizeof(unsigned char));
bytes_received = recv(connected, ptr2, 1,0);// incoming, 0);
printf("bytes received: %d\n", bytes_received);
for(int i = 0; i < rlen; i++){
printf(" i = %d, val = %d\n ", i,*(unsigned char *)(ptr2 + i*sizeof(unsigned char)));
}
Now the Java server sends a number between 1 and 10. I was earlier trying to read the number sent using int incoming = *(int *)ptr1;
but for some reason, occasionally I would get huge values like 51020210
.
To check why this was happening and debug I wrote the code block:
for(int i =0; i<bytes_received; i++){
unsigned char a = *(unsigned char *)(ptr1 + i*sizeof(unsigned char));
printf("Inc: %d", a);
}
It turns out that sometimes, the integer being sent becomes very large.
Why is this happening? On the server side printing out rlen
shows me the right value, but non-deterministically I get random really large values at the client side.
Note that whatever number I receive on the client side has the first number as the value of rlen
.
So for example if rlen
is 6, then the random really large value is something like 689932423
Later the values of rlen
will become very large in the order of 1000s so I need to solve this problem and cannot simply take the first byte of whatever I get on the client side.