Byte Array not size that ".length" says it is - java

Ok, so I have a server cient program(java) for broadcasting the server screen to the client. I convert the image to a byte array and send that to the client. Im having issues sending multiple byte arrays as after the first one is sent and recieved by the client, I get errors for the second byte array. On the server side I have the code:
imageInByte=baos.toByteArray();
outToClient.writeInt(imageInByte.length);
System.out.println(Integer.toString(imageInByte.length));
This tells the client the size of the byte array coming in. On the client I have the code:
int c = inFromServer.readInt();
System.out.println(Integer.toString(c));
This is all well and good and the size that is estimated on the server is the size that the client receives and prints but when I actual try to write the byte array to the dataoutputstream, the byte array that the client receives is nothing like what ".length" estimated.
For example the first byte array is said to be 118207(without sending the actual byte array.
Then when I try to send the first byte array to the client, the client receives it as 118207.
The second one which without trying to actual write the array was 126205 but when I try to write the object the size is -2555936
The third one is supposed to be 125709 but comes out at the client as 1229324289 bytes.
This is driving me crazy and I have a project due next Thursday and cant continue without sorting this out. Any help would be greatly appreciated and if this is in a weird layout or you dont understand me just ask questions .Thanks.

Related

TCP client in Java and server in C

I would like to make a chat application. The client will be written with java and the server will be written with C. On the server side, the message will be sent as struct. On the client side, how do I read and separate the message with Java?
Here is a sample packet structure:
struct s_packet{
int text_color;
char text[TEXTSIZE];
char alias[ALIASIZE];
};
Here is a sample server(in C) send function:
send(iter->client.sockfd, (void *)se_packet, sizeof(s_packet), 0);
Here is a sample client recv function in C:
recv(m_sockfd, (void *)&se_packet, sizeof(s_packet),0);
printf("\x1b[3%dm <%s>: %s \x1b[0m\n", se_packet.text_color, se_packet.alias, se_packet.text);
I can read s_packet and separate in C, but How can I do it in java?
How can i separate like that in Java:
printf("\x1b[3%dm <%s>: %s \x1b[0m\n", se_packet.text_color, se_packet.alias, se_packet.text);
The definite answer is that it won't be so easy. The first thing you should understand is how tcp works. It's a stream oriented protocol and there's no such thing as a "message" in tcp. You just send and receive a stream of bytes.
In your snippet of code recv can finish after reading a part of message sent from the server. Instead you should keep a local buffer in java and drop all the data you've received so far. In a while loop you can detect if a message that is ready for processing was received. If your message is not very big (less than the MTU), then you may get lucky and always receive the whole 'message'. If you are not concerned with that then you may just use java.io.InputStream.read(byte[]) method.
The other thing to consider is how you interpret a message you received. Well you have no other choise but to process it as byte[] in Java. First you may want to read s_packet.text_color. It probably will be placed as first 4 bytes in a message. You can construct int from thoes bytes (see Convert 4 bytes to int for example). But this is not a good practice. This is because you send a binary data that is depends on how your s_packet is represented in memory. In real life you usually don't know what will be the size of int or char, it's platform dependent. Or sometimes the order of bytes inside int itself can differ. Instead you should declare your own serialization protocol and how your message is converted to binary data and vice versa.
Hope it helps.

Errors with data serial transfer DSPIC-interface

I made a matlab Simulink program to program a dspic wich communicates with an inertial unit (by serial link) and a Java interface.
The dspic shoul receive data from inertial unit in which each parameter is a 4 byte array. I made a simulink bloc which converts 4 bytes to single.
After sending these parameters to java interface I use the function to convert this paramter (single) to four bytes in order to send it within the serial port (single to 4 bytes converter).
But the problems is I receive false values. For angles I receive big numbers like 8.658E(12). The values change without giving a significant value.
What should I modify to receive good values?
//N.B: I wanted to insert images but I don't have enough reputation to post them.

Any suggestions on how to wait for an unknown length packet on a socket, and do some processing with its payload bytes as efficiently as possible?

I need to write an UDP server which will wait for packets from uncorrelated devices (max 10000 of them) sending small packets periodically; do some processing with the payload and write the results on SQL. Now I'm done with the SQL part through jdbc, but the payload bytes keep bugging me, how should I access them? Until now I've worked with the payload mapped to a string and then converting the string to hex (two hex chars representing one byte). I'm aware that there's a better way to do this but I don't know it...
Do you not just want to create a DatagramSocket and receive DatagramPackets on it?
You need to specify a maximum length of packet by virtue of the buffer you use to create it, but then you'll be able to find out how much data was actually sent in the packet using getLength().
See the Java Tutorial for more details and an example.

Appending a collection of new bytes

I have a server that sends bytes back to a client app, when the client app receives a finished response from the server i want to gather the bytes before the finish response comes back to the client. How do i append theses bytes back together again.
So when the bytes are sent to the server these bytes are split up into segments of say 100 bytes and when the server sends the bytes back to the client i want to to gather these segments back into its normal form again.
I have had a look at Concatenating to arrays but is there a simple way?
You could create a ByteArrayOutputStream, then write() the arrays to it, and finally use toByteArray().
Guava's Bytes class provides a Bytes.concat method, though it's more useful when you have a fixed number of arrays you want to concatenate than if you're gathering a variable number of arrays to concatenate. ByteArrayOutputStream is probably what you want here, though, based on your description, because it doesn't require you to keep each individual array you receive around in order to concatenate them... you can just add them to the output stream.

Transfer video frames in chunks and then recombine them?

Hope everyone of you doing great.I really need your help.My scenario is given below.
1-I am getting a continuous data (byte array[]) from my camera .
2-Now sending those byte[] through UDP but i have to halve that array because i can't send that big array. (P.S i can't use JMF as its not supported at my device(server side) so have to send byte[] manually through UDP)
3-I am receiving those byte [] chunks at client side.
Now i have following requirement.
-I want a player at the client side which plays my these byte [] chunks but in continuous way.(At client side i can use JMF)
Now i don't know how should i combine all these byte[] chunks at client side so that my video gets play continuously.
Please help as you guys always do.
Best regards
ZB
As an option, you may consider vlcj for video streaming.
Examples how to stream media from camera with VLC player, which may be also of some interest.
If you are transmitting over UDP I assume you are aware of the standard caveats regarding ordering and dropped packets.
I would send the data in the following fashion.
Define a datagram format which has a header and payload with the header being something quite simple like
<packetnumber><timestamp><payloadlength>
<payload>
So you'd create you chunk which is an array of bytes, calculate the payload length, current packet number and timestamp before appending the chunk. Then transmit the whole array and when it's received you can remove the packet number, timestamp and use the payload length to retrieve the data.
Then load the payload into buffer. I'd be tempted to create an object which has the packet number as a key and an array of bytes, then have a doubly linked list of these objects as the buffer. You use the packet number to see where to insert into list and to play back you just keep getting the object with the lowest packet number.
You'll need to define some control data for packet number reseting etc and flow control.
I may have made this more complex by ignoring common libraries but this is the logic I'd follow.

Categories

Resources