Michael Ruberto
Michael Ruberto

Reputation: 3

Address Already in Use Error When Running my Chat Program

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());
}

Upvotes: 0

Views: 175

Answers (1)

gagan singh
gagan singh

Reputation: 1611

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.

Upvotes: 1

Related Questions