wood burning stoves*
The moose likes Sockets and Internet Protocols and the fly likes Copying Multiple Files Over A Socket Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Copying Multiple Files Over A Socket" Watch "Copying Multiple Files Over A Socket" New topic
Author

Copying Multiple Files Over A Socket

J Mangual
Greenhorn

Joined: Nov 15, 2008
Posts: 16
I want to copy several files over the same stream. These files may have different sources and different destinations, so I'm using standard input to read the source and file destination names. As written, the client program takes all the input and write it to the same destination file. I would like it to receive a file, detect end of file, close it and create a new FileOutputStream object. Closing the server socket is not an option because I would like to send many files over the same session.

Client

Server

This is really a sequel to an earlier post, but they suggest posting different questions in different threads.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

You can't detect when the other machine stops sending a file. Unless it closes its socket, which you said you don't want. So you need a protocol which tells you how to tell when you have read the whole file.

One easy protocol is to send the number of bytes in the file first, then to send that many bytes. The receiver will read the number of bytes, then it will read that many bytes.
J Mangual
Greenhorn

Joined: Nov 15, 2008
Posts: 16
All kinds of care has to be made transmitting the file size because read() and write() do not behave reliably. This one seems to work.

Client:


Server:
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

J Mangual wrote:All kinds of care has to be made transmitting the file size because read() and write() do not behave reliably.


Well, not really. I would just use a DataOutputStream to send the file size (without looking I would guess the method is writeLong) and a DataInputStream to read it at the other end. I'm not aware of any unreliable aspects of that.
 
Consider Paul's rocket mass heater.
 
subject: Copying Multiple Files Over A Socket