helloThere
helloThere

Reputation: 1581

Transferring files from Client to Server using TCP

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:

  1. The user selects a file from a predefined directory
  2. Then he can type send-file.ext to send the file to the server The server needs to
  3. get the file from the Client
  4. Save the file in a predefined directory

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

Answers (2)

jveazey
jveazey

Reputation: 5458

The first thing you need to do is to define a protocol. For example...

  1. Each connection to the server should represent a single file.
  2. After connection occurs, the client should pass the file name as the first line.
  3. The client should then pass the size of the file (in bytes) as the second line.
  4. The client should then send the contents of the file.
  5. Finally, the connection should be shut down.

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

blackcompe
blackcompe

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

Related Questions