Reputation: 99
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);
Upvotes: 5
Views: 11967
Reputation: 1
If you are having multiple clients and a single server. Try multi-threading. Sample piece of code:
public static void main(String[] args){
try {
servSocket = new ServerSocket(xxxx);
while(true)
{
socket = servSocket.accept();
ClientNum++;
for(int i=0;i<10;i++){ //this for eg accepts 10 clients, with each client assigned an ID.
if(threads[i]==null){
sockets[i]=socket;
In your "run", you can call each of these clients by their respective ID and perform the reqd function you need. Not sure how clear this is. If needed, I can send you the entire code I have which is kinda similar to what you are doing.
Upvotes: 0
Reputation: 2133
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);
}
Upvotes: 2
Reputation: 13396
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).
Upvotes: 3