Search code examples
javasocketsclient-serverprotocols

Client Server File Transfer Java


I am trying to write an application using Java that will allow me to transfer files between a server and a client that requests the file. I plan to do it using sockets. My algorithm is somewhat like this:

On Server: Create the connection between client and server. Once connected find the file u need to send to client. Then send the size of file to client. Then send file broken down in parts.

On Client After connection is created, ask for the file. Receive the file size, then accept data till u reach file size. Stop.

Please correct me if i am wrong somewhere in the algorithm


Solution

  • This isn't really an "algorithm" question; you're designing a (simple) protocol. What you've described sounds reasonable, but it's too vague to implement. You need to be more specific. For example, some things you need to decide:

    • How does the receiving program know what filename it should save to? Should that be sent through the socket, or should it just ask the user?
    • How is the file size transmitted?
      • Is it a character string? If so, how is its length indicated? (With a null terminator? A newline?)
      • Is it a binary value? If so, how big? (32 bits or 64?) What endianness?
    • What does "broken down in parts" mean? If you're writing to a TCP socket, you don't need to worry about packet boundaries; TCP takes care of that.
    • Does the recipient send anything back, like a success or failure indication?
    • What happens when the whole file has been transmitted?
      • Should both ends assume that the connection must be closed?
      • Or can you send multiple files through a single connection? If so, how does the sender indicate that another file will follow?

    Also, you're using the terms "client" and "server" backward. Typically the "client" is the machine that initiates a connection to a server, and the "server" is the machine that waits for connections from clients.