title: Java: Transfer a file from server to client and from client to server
body: <p>I am a newbie and I want to accomplish file transfer from server to client "do something with it" and then send the file back to the server. The most basic code I am using is here:</p>
  
  <pre><code>import java.io.BufferedInputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.IOException;
  import java.io.OutputStream;
  import java.net.ServerSocket;
  import java.net.Socket;
  
  public class Main {
    public static void main(String[] args) throws IOException {
      ServerSocket servsock = new ServerSocket(123456);
      File myFile = new File("s.pdf");
      while (true) {
        Socket sock = servsock.accept();
        byte[] mybytearray = new byte[(int) myFile.length()];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
        bis.read(mybytearray, 0, mybytearray.length);
        OutputStream os = sock.getOutputStream();
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
        sock.close();
      }
    }
  }
  
  The client module
  
  import java.io.BufferedOutputStream;
  import java.io.FileOutputStream;
  import java.io.InputStream;
  import java.net.Socket;
  
  public class Main {
    public static void main(String[] argv) throws Exception {
      Socket sock = new Socket("127.0.0.1", 123456);
      byte[] mybytearray = new byte[1024];
      InputStream is = sock.getInputStream();
      FileOutputStream fos = new FileOutputStream("s.pdf");
      BufferedOutputStream bos = new BufferedOutputStream(fos);
      int bytesRead = is.read(mybytearray, 0, mybytearray.length);
      bos.write(mybytearray, 0, bytesRead);
      bos.close();
      sock.close();
    }
  } 
  </code></pre>
  
  <p>Got it from this website: <a href="http://www.java2s.com/Code/Java/Network-Protocol/TransferafileviaSocket.htm" rel="nofollow">http://www.java2s.com/Code/Java/Network-Protocol/TransferafileviaSocket.htm</a></p>
  
  <p>I understand how this works but I don't know how to send a file back to the server. 
  Please help.</p>