aspose file tools*
The moose likes Sockets and Internet Protocols and the fly likes First steps with networking: best practice for sending file over socket Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "First steps with networking: best practice for sending file over socket" Watch "First steps with networking: best practice for sending file over socket" New topic
Author

First steps with networking: best practice for sending file over socket

Emanuele Mazzante
Ranch Hand

Joined: Jan 14, 2014
Posts: 50
    
    1
Hello,

I'm studying streams and networking and I'm trying a simple program to exchange files between server and client. I found this post very useful.

This is my code that is almost identical:


These are my doubts:
1)What is the best approach to read data from the stream? The first one or the alternative one?
2)What is the recommended size for the buffer?
3)Finally (I know that is a stupid question but I don't get it) when I using the method readUTF how does it know exactly when file name end and when data file start? The writeUTF method insert markers?

Thanks for the help, I appreciate it very much.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18987
    
    8

Reading the whole file into memory is a risky strategy, since if the file is very large then your program may run out of memory. It's even possible for files to be larger than Integer.MAX_VALUE, in which case your program would truncate the file.

The buffer size? That depends on a variety of things which are specific to your environment. Once you get the code working you could try different values and see what difference they make.

As for exactly how readUTF and writeUTF work, I have no idea. And you don't need to know either, all you need to know is that they do what the documentation says. However if you really want to know, you could look at the source code. You can find it in the src.zip file which is in your Java install directory.
Emanuele Mazzante
Ranch Hand

Joined: Jan 14, 2014
Posts: 50
    
    1
Thank Paul for your attention and help.

Could you do a small example of how to do not load the whole file into memory? And sorry, what about the protocol to be used for client-server communication? I have seen that often uses the type FileName, FileLength and FileData.

The author of the code in the linked post read data from the socket with but also the commented out seems to work properly The first one give you more control over the data read but there are other reasons to prefer one rather then the other one?

Thank you again.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: First steps with networking: best practice for sending file over socket