Vimal Arjun
Vimal Arjun

Reputation: 29

Multithreaded file transfer via socket in java

I want to receive chunks of a file from multi-thread and write in orderly.

I have a server file on one system that send a file into 4 chunks through 4 thread now i have a client program on another machine i want to receive that files with 4 threads and write that to disk in correct order. I have no idea to receive and write in order can you help?!

Thanks for advance!!

Upvotes: 0

Views: 63

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35096

Except possibly in an extraordinary case, there is absolutely no reason to do this. A single thread can retrieve data from a Socket far faster than the data is transmitted.

But if you did want to do this, you could do something like

public static class Multireceiver implements Runnable {
  static AtomicInteger step = new AtomicInteger(0);
  InputStream s;
  int spot;
  public Multireceiver (InputStream in) {
    s = in;
  }
  public void run() {
    spot = step.incrementAndGet();
    //grab a bunch of bytes and put them in an object with the step number attached
  }

}

Then you just need to order your partial downloads by spot and reassemble the data. But again, all of this is normally unnecessary

Upvotes: 3

Related Questions