java - 运行我的聊天程序时出现地址已在使用错误

标签 java sockets networking ip-address

我正在尝试创建一个聊天程序,但遇到了一些问题。我试图通过运行它的两个实例(一个是客户端,一个是服务器)来在我的机器上测试它。发生这种情况时,在创建第二个实例后,我收到 BindException 错误,指出该地址已在使用中。我认为问题的根源可能是,由于聊天只是较大应用程序的一小部分,因此我试图制作一个具有服务器和客户端功能的程序,并且用户在加载应用程序时选择一个程序。下面,我附上了相关代码。任何和所有的帮助将不胜感激! (对于格式错误表示歉意)

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

最佳答案

您正在打开一个服务器套接字

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

这将开始监听端口 9999。

然后,您再次在客户端代码中打开服务器端口。

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

为什么客户端需要一个serversocket? 这会导致您在问题中提到的问题。

关于java - 运行我的聊天程序时出现地址已在使用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50650654/

相关文章:

c++ - 套接字在 32739 个连接后无法关闭

c - 创建将同时为 200 多个客户端发送/接收任务的服务器时,使用选择或多线程(或两者)更好吗

java - 如何强制在抽象类的所有子类中定义构造函数

java - RecyclerView onViewDetachedFromWindow 导致问题

sockets - tcp 两端尝试同时连接

c# - 如何强制二进制应用程序使用 C# 工具中的 SOCKS 代理?

networking - linux上套接字的连接超时是多少

macos - 什么是 acvpnagent?

java - 为什么@UniqueConstraint在 hibernate 中不起作用?

java - 模拟对象没有为我服务?