0

I'm trying to create a chat program and I'm having a bit of an issue. I'm trying to test it on my machine by running two instances of it (one a client, one a server). When this happens, after I create the second instance, I get a BindException error saying the address is already in use. What I think may be the source of the problem is that as chatting is a smaller part of a larger application, I'm trying to make one program with both Server and Client capabilities, and the user picks one when they load up the application. Below, I have attached the relevant code. Any and all help would be appreciated! (Apologies for poor formatting)

public ChatPanel(){
  //Sets up main panel and variables
  this.setBackground(new Color(0, 155, 228));
  this.setFocusable(false);  
  this.setLayout(new BorderLayout());
  textBox = new JTextField();
  chatBox = new MessagePanel();
  this.add(chatBox, BorderLayout.CENTER);
  this.add(textBox, BorderLayout.SOUTH);
  begin();}

  public void begin() {
  String[] options = {"Server", "Client"};
  int entry = JOptionPane.showOptionDialog(null, "Server or Client?", "Setup",
        JOptionPane.YES_NO_OPTION, JOptionPane.NO_OPTION, null, options, options[0]);
  thisIsAServer = !(entry == 1);
  showMessage("" + entry);
  if(thisIsAServer) startRunning();
  else {
     serverIP = (String)JOptionPane.showInputDialog(null, "Enter the IP Address of the Host ", "Connect to Host",
           JOptionPane.PLAIN_MESSAGE, null, null, "");
     startRunningClient();
  }
  }

  //Server
  private void startRunning() {
  try {
     server = new ServerSocket(9999, 100);
     while(true) {
        try {
           waitForConnection();
           setUpStreams();
           whileChatting();
        } catch(EOFException eof) {
           showMessage("Chat Ended");
        }finally {
           close();
        }
     }
  } catch (IOException e) {e.printStackTrace();}
  }

  //Server
  private void waitForConnection() throws IOException{
  System.out.println("1");
  showMessage("Waiting for connection");
  connection = server.accept();
  System.out.println("1.5");
  showMessage("Connected to: " + connection.getInetAddress().getHostName());
  }

  //Server
  private void setUpStreams() throws IOException{
  System.out.println("2");
  output = new ObjectOutputStream(connection.getOutputStream());
  output.flush();
  input = new ObjectInputStream(connection.getInputStream());
  showMessage("Streams successfully setup");
  }

  //Client
  private void setUpStreamsC() throws IOException{
  System.out.println("2");
  output = new ObjectOutputStream(connection.getOutputStream());
  output.flush();
  input = new ObjectInputStream(connection.getInputStream());
  showMessage("Streams successfully setup");
  }

  //Server
  private void whileChatting() throws IOException{
  System.out.println("3");
  String message = "Hello World";
  sendMessage(message);
  do {
     try {
        message = (String) input.readObject();
        showMessage(message);
     }catch(ClassNotFoundException cnfe) {
        showMessage("Error");
     }
  }while(!message.equals("CLIENT - END") || !message.equals("SERVER - END"));
  }

  //Client
  private void whileChattingC() throws IOException{
  System.out.println("3");
  String message = "Hello World";
  sendMessage(message);
  do {
     try {
        message = (String) input.readObject();
        showMessage(message);
     }catch(ClassNotFoundException cnfe) {
        showMessage("Error");
     }
  }while(!message.equals("CLIENT - END") || !message.equals("SERVER - END"));
  }

  //Server
  private void close() {
  try {
     output.close();
     input.close();
     connection.close();
  } catch (IOException e) {e.printStackTrace();}
  }

  //Server
  public void sendMessage(String message) {
  String name = "CLIENT";
  if(thisIsAServer) name = "CLIENT";

  try {
     output.writeObject(name + " - " + message);
     output.flush();
     showMessage("\n " + name + " - " + message);
  }catch(IOException e) {chatBox.getChatBox().append("\nERROR");}

  }

  //Server
  private void showMessage(String message) {
  chatBox.getChatBox().append(message);
  }

  private void startRunningClient() {
  try {
     server = new ServerSocket(9999, 100);
     while(true) {
        try {
           connectToServer();
           setUpStreamsC();
           whileChattingC();
        } catch(EOFException eof) {
           showMessage("Chat Ended");
        }finally {
           close();
        }
     }
  } catch (IOException e) {e.printStackTrace();}
}

private void connectToServer() throws IOException{
  showMessage("Attempting connection... \n");
  connection = new Socket(InetAddress.getByName(serverIP), 9999);
  showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
  • What address do you use? If you have a copy of the program running already bound to the same address, you'll get this error. Kill your existing app properly before launching a new instance. – markspace Jun 01 '18 at 20:35
  • 1
    `ServerSockets` are listening on a dedicated port. However only one Socket can listen on a port at a time. There are some reseverd ports as well an some which are common for certain application. For example a webserver hostinga webside will most likely listen on port 80. If the port you want to listen on is already in use you get the exception you mentioned in your post. – L.Spillner Jun 01 '18 at 20:39
  • 2
    Possible duplicate of [Address already in use: JVM\_Bind java](https://stackoverflow.com/questions/2772701/address-already-in-use-jvm-bind-java) – Olaf Kock Jun 02 '18 at 07:24

1 Answers1

1

You are open a server socket at

//Server
private void startRunning() {
try {
   server = new ServerSocket(9999, 100);

This starts listening on port 9999.

Then you again open a server port in the client code.

 private void startRunningClient() {
  try {
     server = new ServerSocket(9999, 100);

Why do you need a serversocket on the client side? This cause the issue that you mentioned in your question.

gagan singh
  • 1,591
  • 1
  • 7
  • 12