0

I am working on an assignment for my Networks class and we have to use sockets to download an image from the web. The idea is to open 5 separate sockets, run them concurrently in separate threads and have them each download a part of the file then stitch them back together after getting the different parts. What I am confused about is how would the second thread know to start the stream at the point the first one ended? Like I have:

InputStream is = new BufferedInputStream(socket.getInputStream());
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
String request = "GET " + path + " HTTP/1.0\n\r\n\r";
dout.write(request.getBytes());

Then the loop that reads the stream:

while ((bytes = is.read(buffer)) != -1)

But if this is happening every time a run a new thread and create a new socket/TCP connection, how can set the stream to start at the point the last stream stopped? To clarify a bit more, the first thread should create a file called image.jpg.part1 then the second image.jpg.part2 and so on. Then we combine the parts into the original image.

Thanks!

  • Can you use a [range request header](https://en.wikipedia.org/wiki/Byte_serving) and hardcode the amount of bytes each part should download? (You would need to know the filesize to make this work, and the server needs to accept the header) – Kevin L Sep 15 '16 at 20:54
  • Yes I have the file size and am hardcoding the byte chunk sizes. Would the range request header be in the GET request? What would that look like? – user3522016 Sep 15 '16 at 21:11
  • The spec for the Range request header is specified here: https://tools.ietf.org/html/rfc7233#section-3. See also: http://stackoverflow.com/questions/8293687/sample-http-range-request-session – joev Sep 15 '16 at 21:46
  • I'm not much for networking in Java, but couldn't you, get the entire files size and have each thread read from specific sections of the file into your part files, and then read each of these into their own byte buffer. Finally, combining all of these byte buffers into one file. – parabolah Sep 16 '16 at 01:47
  • Yes, that's the idea. I have tried using the range option in the request header but to no avail yet, though this puts me on the right track. Thanks for all the feedback, it is much appreciated! – user3522016 Sep 17 '16 at 01:40

0 Answers0