title: How did the server avoid "address already in use error" after the first or second message sending (java multithreaded socket programming)
body: <p>I am trying to create a text messaging program with three files (main function file, client file, server file)</p>
  
  <p>If "-l" is present on the command line, it will run as a server, otherwise it will run as a client</p>
  
  <p>Command line arguments to run server:</p>
  
  <pre><code>java DirectMessengerCombined -l 3000
  </code></pre>
  
  <p>Command line arguments to run client:</p>
  
  <pre><code>java DirectMessengerCombined 3000
  </code></pre>
  
  <p>Text of error:</p>
  
  <pre><code>java.net.BindException: Address already in use
  at java.net.PlainSocketImpl.socketBind(Native Method)
  at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
  at java.net.ServerSocket.bind(ServerSocket.java:375)
  at java.net.ServerSocket.&lt;init&gt;(ServerSocket.java:237)
  at java.net.ServerSocket.&lt;init&gt;(ServerSocket.java:128)
  at DirectMessengerServer.run(DirectMessengerServer.java:41)
  at DirectMessengerServer.runSend(DirectMessengerServer.java:111)
  at DirectMessengerServer.run(DirectMessengerServer.java:58)
  at DirectMessengerServer.&lt;init&gt;(DirectMessengerServer.java:16)
  at DirectMessengerCombined.main(DirectMessengerCombined.java:21)
  </code></pre>
  
  <p>Screenshot of error (server on left, client on right):</p>
  
  <p><a href="https://i.stack.imgur.com/qyZE3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qyZE3.png" alt="server is left window, client is right window"></a></p>
  
  <p>The problem with the screenshot is that the left window (server) was able to send and recieve text messages to the client until the server sends the "hello" message. </p>
  
  <p>Code of main Server file:</p>
  
  <pre><code>import java.io.*;
  import java.net.*;
  import java.util.*;
  import javax.imageio.IIOException;
  public class DirectMessengerServer
  {
  
      private String[] serverArgs; // &lt;-- added variable
      private static Socket socket;
      public boolean keepRunning = true;
  
      public DirectMessengerServer(String[] args) throws IOException 
      {
          // set the instance variable
          this.serverArgs = args;
          run();
      }
  
        public String[] ServerRun(String[] args) throws IOException 
        {
            //How do I get the String[] args in this method be able to access it in the run methods?
          serverArgs = args;
          serverArgs = Arrays.copyOf(args, args.length);
  
          return serverArgs;
  
        }
  
  
  
  
  Thread ListeningLoop = new Thread();    
  //run method of ServerRecieve
  public void run() throws IOException
  {  
  
  
      try
      {
          int port_number1 = Integer.valueOf(serverArgs[1]);
          ServerSocket serverSocket = new ServerSocket(port_number1);
          socket = serverSocket.accept(); 
          while(keepRunning)
          {
  
              //Reading the message from the client
  
  
  
              InputStream is = socket.getInputStream();
              InputStreamReader isr = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(isr);
              String MessageFromClient = br.readLine();
              System.out.println("Message received from client: "+ MessageFromClient);
  
             // ServerSend.start();
  
              runSend();
  
  
  
          }
      } 
      catch (IOException e)
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      finally
      {
      }
  }
  
  Thread ServerSend = new Thread ();
  
  //Run method of ServerSend
  public void runSend()
  {   
      while(keepRunning)
      {
          System.out.println("Server sending thread is now running");
          try
          {         
  
              //Send the message to the server
              OutputStream os = socket.getOutputStream();
              OutputStreamWriter osw = new OutputStreamWriter(os);
              BufferedWriter bw = new BufferedWriter(osw);
  
              //creating message to send from standard input
              String newmessage = "";
              try 
              {
                  // input the message from standard input
                  BufferedReader input= new BufferedReader( 
                          new InputStreamReader(System.in));
                  String line = "";
  
                  line= input.readLine(); 
                      newmessage += line + " ";
  
              }
              catch ( Exception e )
              {
                  System.out.println( e.getMessage() );
              }
              String sendMessage = newmessage;
              bw.write(sendMessage + "\n");
              bw.flush();
              System.out.println("Message sent to client: "+sendMessage);
              run();
          }
  
  
          catch (IOException e) 
          {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          finally
          {
  
          }
      }
  }
  
  
  }
  </code></pre>
  
  <p>Code of Client file:</p>
  
  <pre><code>import java.io.*;
  import java.net.*;
  import java.util.*;
  import static java.nio.charset.StandardCharsets.*;
  public class DirectMessengerClient
  {
      private String[] clientArgs; // &lt;-- added variable
      private static Socket socket;
      public boolean keepRunning = true;
      public DirectMessengerClient(String[] args) throws IOException 
      {
          // set the instance variable
          this.clientArgs = args;
          run(args);
  
  
      }
      public String[] ClientRun(String[] args)
      {
          clientArgs = args;
          clientArgs = Arrays.copyOf(args, args.length);
          return clientArgs;
      }
  
      Thread ClientSend = new Thread();   
      public void run(String args[]) throws IOException
      {   
          System.out.println("Client send thread is now running");
          while(keepRunning)
          {             
               String port_number1= args[0];
               System.out.println("Port number is: " + port_number1);
               int port = Integer.valueOf(port_number1);
               String host = "localhost";
               InetAddress address = InetAddress.getByName(host);
               socket = new Socket(address, port);
  
  
               //Send the message to the server
               OutputStream os = socket.getOutputStream();
               OutputStreamWriter osw = new OutputStreamWriter(os);
               BufferedWriter bw = new BufferedWriter(osw);
  
               //creating message to send from standard input
               String newmessage = "";
               try 
               {
                   // input the message from standard input
                   BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
                   String line = "";
  
                   line= input.readLine(); 
                   newmessage += line + " ";
  
  
                }
                catch ( Exception e )
                {
                       System.out.println( e.getMessage() );
                }
                  String sendMessage = newmessage;
                  bw.write(sendMessage + "\n");
                  bw.flush();
                  System.out.println("Message sent to server: "+sendMessage);
                  runClientRead(args);
              }
  
          }
  
  
      Thread ClientRead = new Thread();
      public void runClientRead(String args[]) throws IOException
      {   
          System.out.println("Client recieve/read thread is now running");
  
              //Integer port= Integer.valueOf(args[0]);
              //String host = "localhost";
              //InetAddress address = InetAddress.getByName(host);
              //socket = new Socket(address, port);
  
              //Get the return message from the server
              InputStream is = socket.getInputStream();
              InputStreamReader isr = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(isr);
              String MessageFromServer = br.readLine();
              System.out.println("Message received from server: " + MessageFromServer);
  
      }
  }
  </code></pre>
  
  <p>Code of main function file:</p>
  
  <pre><code>  import java.io.IOException;
  
  public class DirectMessengerCombined
  {
      public static void main(String[] args) throws IOException
      {
  
          DirectMessengerClient client1 = null;
          DirectMessengerServer server1 = null;
  
            for (int i = 0; i &lt; args.length; i++)
            {
  
                if (args.length == 1) 
                {
                   client1  = new DirectMessengerClient(args);
                   client1.ClientRun(args);
                }
                else if (args.length == 2)
                {
                   server1 = new DirectMessengerServer(args);
                   server1.ServerRun(args);
                }
             i=args.length + 20;
            } 
      }
  
  }
  </code></pre>
  
  <p>My question is not only how to resolve the error (there's plenty of other questions that covered this) but why wasn't the error triggered the first time the messages were sent/received to/from the server?</p>