title: File cannot be sent to server from client using sockets in Java
body: <p>I am trying to write some code that allows clients to send files to server. But I cannot send files with this code.</p>
  
  <p>Server:</p>
  
  <pre><code>package Server;
  
  import java.io.IOException;
  import java.net.ServerSocket;
  import java.net.Socket;
  
  
  public class SimpleServer {
  public static int serverThreadCount = 0;
  public static final int maxUser = 10;
  public static String[] username = new String[maxUser];
  public static String[] password = new String[maxUser];
  public static String[] online = new String[maxUser];
  
  
  public static void main(String[] args) {
      int id = 1;
  
      username[0] = "a";
      username[1] = "b";
      username[2] = "c";        
      username[3] = "d";
      username[4] = "e";
      username[5] = "f";
      username[6] = "g";
      username[7] = "h";
      username[8] = "i";
      username[9] = "j";
  
      for(int i=0; i&lt;maxUser; i++)
      {
          password[i] = "123";
          online[i] = "free";
      }
  
      try
      {
          ServerSocket ss = new ServerSocket(7777);
          System.out.println("Server has successfully been started.");
  
          while(true) 
          {
              Socket socket = ss.accept();
              new Thread(new ServerThread(socket, id)).start();
              serverThreadCount++;
              System.out.println("Client " + id + " is now connected to the server.");
              id++;
          }
      }
      catch(IOException e)
      {
          System.err.println("IOException in serverSocket");
          e.printStackTrace();
      }
  }
  
  public static boolean verifyLogin(String u, String p)
  {
      for(int i=0; i&lt;maxUser; i++)
      {
          if(username[i].equals(u) &amp;&amp; password[i].equals(p)) return true;
      }
      return false;
  }
  
  public static void setOnline(String name)
  {
      for(int i=0; i&lt;maxUser; i++)
      {
          if(online[i].equals("free")) 
          {
              online[i] = name;
              break;
          }
      }
  }
  
  public static boolean isOnline(String u)
  {
      for(int i=0; i&lt;maxUser; i++)
      {
          if(online[i].equals(u)) return true;
      }
      return false;
  }
  }
  </code></pre>
  
  <p>ServerThread:</p>
  
  <pre><code>package Server;
  
  import java.io.BufferedInputStream;
  import java.io.BufferedReader;
  import java.io.DataInputStream;
  import java.io.DataOutputStream;
  import java.io.EOFException;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.io.OutputStream;
  import java.io.PrintWriter;
  import java.io.UTFDataFormatException;
  import java.net.Socket;
  
  class ServerThread implements Runnable{
      private Socket socket;
      private InputStream is;
      private OutputStream os;
      private boolean validUser = false;
      private String user; 
  
  private int id = 0;
  
  public ServerThread(Socket socket, int id)
  {
      this.socket = socket;
      this.id = id;
  
      try
      {
          this.is = this.socket.getInputStream();
          this.os = this.socket.getOutputStream();
      }
      catch(IOException e)
      {
          System.err.println("Cannot connect properly to this client " + id);
          e.printStackTrace();
      }
  }
  
  @Override
  public void run()
  {
      BufferedReader br = new BufferedReader(new InputStreamReader(this.is));
      PrintWriter pw = new PrintWriter(this.os);
  
      pw.println("Your id is: " + this.id);
      pw.flush();
  
      String s;
  
      while(true)
      {
          try
          {
              if((s = br.readLine()) != null)
              {
                  if(s.startsWith("login"))
                  {
                      String pwd = s.substring(6, 9);
                      String uname = s.substring(10);
                      if(SimpleServer.isOnline(uname))
                      {
                          pw.println("You already are online.");
                          pw.flush();
                      }
                      validUser = SimpleServer.verifyLogin(uname, pwd);
                      if(validUser)
                      {
                          this.user = uname;
                          SimpleServer.setOnline(uname);
                          pw.println(uname + " has successfully logged in to server");
                          pw.flush();
                      }
                      else
                      {
                          pw.println("Invalid username or password! Try again!");
                          pw.flush();
                      }
  
                  }
  
                  if(s.equals("logout"))
                  {
                      if(!validUser)
                      {
                          pw.println("Please login to continue");
                          pw.flush();
                      }
                      System.out.println(id + " is going offline");
                      this.validUser = false;
                      break;
                  }
  
                  if(s.equals("online"))
                  {
                      if(!validUser)
                      {
                          pw.println("Please login to continue");
                          pw.flush();
                      }
                      String activePeers = "";
                      for(String peer: SimpleServer.online)
                      {
                          if(peer.equals("free")) break; 
                          activePeers += peer + ", ";
                      }
                      pw.println(activePeers);
                      pw.flush();
                  }
  
                  if(s.equals("sendfile"))
                  {
                      if(!validUser)
                      {
                          pw.println("Please login to continue");
                          pw.flush();
                      }
                      receiveFile();
                      break;
                  }
  
  
                  {
                      System.out.println(id + ": " + s);
                      pw.println("received successfully: " + s);
                      pw.flush();
                  }
              }
              else
              {
                  System.out.println(id + " has terminated.");
                  break;
              }
          }
          catch(IOException e)
          {
              System.err.println("An IO exception has taken place");
              e.printStackTrace();
              break;
          }
      }
  
      try
      {
          this.is.close();
          this.os.close();
          this.socket.close();
      }
      catch(IOException e)
      {
          System.err.println("Cannot close connection");
          e.printStackTrace();
      }
  
      SimpleServer.serverThreadCount--;
      System.out.println(id + " is going offline");
      System.out.println("No of curent active seeds is: " + SimpleServer.serverThreadCount);
  }
  
  public void receiveFile()
  {
      int bytesRead;
  
      try
      {
          DataInputStream dis = new DataInputStream(socket.getInputStream());
          String fileName = dis.readUTF();
          OutputStream outputStream = new FileOutputStream(fileName + "received_from_" + user);
          long size = dis.readLong();
          byte[] buffer = new byte[1024];
          while(size &gt; 0 &amp;&amp; (bytesRead = dis.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
          {
              outputStream.write(buffer, 0, bytesRead);
              size -= bytesRead;
          }
          outputStream.close();
          dis.close();
      }
      catch(EOFException eOFException)
      {
          System.err.println("End of file exception has occured.");
          eOFException.printStackTrace();
      }
      catch(UTFDataFormatException uTFDataFormatException)
      {
          System.err.println("UTFDataFormatException has occured.");
          uTFDataFormatException.printStackTrace();
      }
      catch(IOException ioException)
      {
          System.err.println("IOException has occured.");
          ioException.printStackTrace();
      }
  }
  
  public void sendFile(String fileName)
  {
      try
      {
          File file = new File(fileName);
          byte[] bytearray = new byte[(int) file.length()];
          FileInputStream fis = new FileInputStream(file);
          BufferedInputStream bis = new BufferedInputStream(fis);
          DataInputStream dis = new DataInputStream(bis);
          dis.readFully(bytearray, 0, bytearray.length);
          OutputStream os = this.socket.getOutputStream();
          DataOutputStream dos = new DataOutputStream(os);
          dos.writeUTF(file.getName());
          dos.writeLong(bytearray.length);
          dos.write(bytearray, 0, bytearray.length);
          dos.flush();
          System.out.println("Sending file is a success!");
      }
      catch(FileNotFoundException fileNotFoundException)
      {
          System.err.println("File mentioned does not exist.");
          fileNotFoundException.printStackTrace();
      }
      catch(EOFException eofException)
      {
          System.err.println("End of file exception has occured.");
          eofException.printStackTrace();
      }
      catch(IOException ioException)
      {
          System.err.println("IOException has occured.");
          ioException.printStackTrace();
      }
  }
  }
  </code></pre>
  
  <p>Client:</p>
  
  <pre><code>package Client;
  
  import java.io.BufferedInputStream;
  import java.io.BufferedReader;
  import java.io.DataInputStream;
  import java.io.DataOutputStream;
  import java.io.EOFException;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.io.OutputStream;
  import java.io.PrintWriter;
  import java.net.Socket;
  import java.net.UnknownHostException;
  import java.util.NoSuchElementException;
  import java.util.Scanner;
  
  
  public class SimpleClient {
      private static Socket socket;
      private static BufferedReader br;
      private static PrintWriter pw;
      private static String fileName;
  
  public static void main(String[] args)
  {
      Scanner scanner = new Scanner(System.in);
      String send = "", rec = "";
  
      try
      {
          socket = new Socket("localhost", 7777);
  
          br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          pw = new PrintWriter(socket.getOutputStream());
      }
      catch(UnknownHostException unknownHostException)
      {
          System.err.println("I don't know this" + socket.getPort() +"host!");
          unknownHostException.printStackTrace();
          System.exit(1);
      }
      catch(IOException e)
      {
          System.err.println("An IO exception has occured when initializing client.");
          closeconn();
          System.exit(1);
      }
  
      try
      {
          rec = br.readLine();
          if(rec != null)
          {
              System.out.println("Server: " + rec);
          }
          else
          {
              System.err.println("Cannot read from socket.");
              closeconn();
              System.exit(0);
          }
      }
      catch(IOException e)
      {
          System.err.println("Cannot read from socket.");
          closeconn();
          System.exit(0);
      }
  
      while(true)
      {
          System.out.println("Tell something to server:");
          try
          {
              send = scanner.nextLine();
              if(send.equals("sendfile"))
              {
                  sendFile();
                  break;
              }
          }
          catch(NoSuchElementException noSuchElementException)
          {
              noSuchElementException.printStackTrace();
          }
          catch(IllegalStateException illegalStateException)
          {
              illegalStateException.printStackTrace();
          }
  
          pw.println(send);
          pw.flush();
  
          try
          {
              rec = br.readLine();
              if(rec != null)
              {
                  System.out.println("Server: " + rec);
              }
              else
              {
                  System.err.println("Cannot read from socket.");
                  break;
              }
          }
          catch(IOException e)
          {
              System.err.println("Cannot read from Socket");
              e.printStackTrace();
              break;
          }
  
          if(send.equals("BYE"))
          {
              System.out.println("See you later.");
              break;
          }
      }
      closeconn();
  }
  
  private static void closeconn()  {
      try
      {
          br.close();
          pw.close();
          socket.close();
      }
      catch(IOException e)
      {
          System.err.println("An error occured when closing client.");
          e.printStackTrace();
      }
  }
  
  private static String some()
  {
      return "success!";
  }
  
  private static void sendFile()
  {
      try
      {
          System.out.print("Please enter file name: ");
          fileName = br.readLine();
  
          File file = new File(fileName);
          byte[] bytearray = new byte[(int)file.length()];
          FileInputStream fis = new FileInputStream(file);
          BufferedInputStream bis = new BufferedInputStream(fis);
  
          DataInputStream dis = new DataInputStream(bis);
          dis.readFully(bytearray, 0, bytearray.length);
  
          OutputStream os = socket.getOutputStream();
  
          DataOutputStream dos = new DataOutputStream(os);
          dos.writeUTF(file.getName());
          dos.writeLong(bytearray.length);
          dos.write(bytearray, 0, bytearray.length);
          dos.flush();
          System.out.println("success!");
      }
      catch(FileNotFoundException fileNotFoundException)
      {
          System.err.println("File does not exist!");
          fileNotFoundException.printStackTrace();
      }
      catch(NullPointerException nullPointerException)
      {
          nullPointerException.printStackTrace();
      }        
      catch(EOFException eOFException)
      {
          System.err.println("End of file exception.");
          eOFException.printStackTrace();
      }
      catch(IOException iOException)
      {
          iOException.printStackTrace();
      }
  }
  
  public static void receiveFile(String fileName)
  {
      try
      {
          int bytesRead;
          InputStream is = socket.getInputStream();
  
          DataInputStream dis = new DataInputStream(is);
  
          fileName = dis.readUTF();
          OutputStream os = new FileOutputStream("received_from_server_" + fileName);
          long size = dis.readLong();
          byte[] buffer = new byte[1024];
          while(size &gt; 0 &amp;&amp; (bytesRead = dis.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
          {
              os.write(buffer, 0, bytesRead);
              size -= bytesRead;
          }
          os.close();
          is.close();
      }
      catch(IOException iOException)
      {
          iOException.printStackTrace();
      }
  }
  }
  </code></pre>
  
  <p>To login, login password username is to be typed.</p>
  
  <p>On receiving "sendfile" from the client, the class Client call sendFile method which turns desired file into byte array. On receiving "sendfile" from Client Server calls the method receiveFile that accepts and build the file sent from client. </p>