I can display a single image received, but now I want to receive and write multiple images on my disk which will be sent from Android client after every 5 seconds.
Socket sock = servsock.accept();
dataInputStream = new DataInputStream(sock.getInputStream());
dataOutputStream = new DataOutputStream(sock.getOutputStream());
System.out.println("Accepted connection : " + sock);
dataInputStream = new DataInputStream(sock.getInputStream());
byte[] base64=dataInputStream.readUTF().getBytes();
byte[] arr=Base64.decodeBase64(base64);
FileOutputStream imageOutFile = new FileOutputStream("E:\\image.jpeg");
imageOutFile.write(arr);
Reading Binary Data from a Socket The simplest protocol which we can define is called TLV (Type Length Value). It means that every message written to the socket is in the form of the Type Length Value. So we define every message sent as: A 1 byte character that represents the data type, like s for String.
Behavior for sockets: The read() call reads data on a socket with descriptor fs and stores it in a buffer. The read() all applies only to connected sockets. This call returns up to N bytes of data. If there are fewer bytes available than requested, the call returns the number currently available.
You'll need to build a protocol between your client and the server.
If the image size is constant you just have to loop over the input-stream and keep buffering until you get the fixed number of bytes and write all the already buffered image.
Otherwise you'll need to add some metadata indicating the size of the images; e.g. you could use a simple format like this :
[size1][image1][size2][image2][size3][image3]
with [size-i] occupying a fixed amount of space and [image-i] the size of the ith image.
But above all don't be tempted to do such a naive protocol as processing an image, sleeping 5 seconds and retrieving the next one because the exact time could vary a lot between each image due to client, network or the server (your code and/or the file-system).
Little changes:
Socket sock = servsock.accept();
dataInputStream = new DataInputStream(sock.getInputStream());
dataOutputStream = new DataOutputStream(sock.getOutputStream());
System.out.println("Accepted connection : " + sock);
int imagesCount = dataInputStream.readInt();
for (int imgNum = 0; imgNum < imagesCount; imgNum++) {
int imgLen = dataInputStream.readInt();
byte[] base64 = new byte[imgLen];
dataInputStream.readFully(base64);
byte[] arr = Base64.decodeBase64(base64);
FileOutputStream imageOutFile = new FileOutputStream("E:\\image"+imgNum+".jpeg");
imageOutFile.write(arr);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With