Reputation: 1581
Hello everyone I'm doing a school project and I need to make a TCP Server/Client to transfer files from the client to the Server using the TCP protocol.
I already know how to make a TCP server and client sending messages and objects.
What I need is:
How do i go about this? If I fetch a file from the users hard drive, how do i make that file into to bytes and then send to the server. How does the server know it is a file and save the file with its original name?
Thanx
Upvotes: 0
Views: 4249
Reputation: 5458
The first thing you need to do is to define a protocol. For example...
Now, you have to do the coding for the client. You can read the contents of the file using FileInputStream. Then, send the meta data plus the contents over the socket using the OutputBuffer on the socket.
Finally, the server. Whenever a client connects, you know what the first two lines are going to be. So, read in the first line and create a new file based on the file name. Then, read in the second line. Finally, read X number of bytes from the socket and write those bytes to the file, where X is the size in bytes from the second line.
By having the second line, you know when you are done with the socket. Plus, in case the socket dies or blocks - for whatever reason - you know something is wrong with the transfer and can abort.
Upvotes: 2
Reputation: 3190
Use ObjectOutputStream to send an instance of File over the socket and File.getName to get the file name. File is Serializable so you don't need to convert an instance to bytes. See this example for more help.
//client
String filename = "";
File f = new File(filename);
Socket sock = new Socket();
ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeObject( f );
//server
ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
File f = (File)ois.readObject();
String filename = f.getName();
Upvotes: -1