2016-02-23 85 views
0

我有一個服務器項目和一個客戶端項目。當服務器運行從客戶端的第一個連接正常工作。在第二次連接時,服務器會觸發「java.net.BindException:已在使用的地址:JVM_Bind」錯誤。有沒有辦法在同一端口上添加更多連接?java.net.BindException:已在使用的地址:JVM_Bind多客戶端服務器

服務器:

public class Main { 

public static void main(String[] args) throws IOException, ClassNotFoundException { 

    Socket pipe = null; 
    while(true){ 

    ServerSocket s = new ServerSocket(2345); 
    pipe = s.accept(); 

    Connection c = new Connection(pipe); 
    c.start(); 

    } 
} 

}

public class Connection extends Thread{ 

private Socket socket = null; 

Mensch jim = null; 
ObjectInputStream input = null; 
ObjectOutputStream output = null; 
ServerSocket s = null; 

public Connection(Socket s){ 
    socket = s; 
} 
    public void run(){ 
     try { 
     input = new ObjectInputStream(socket.getInputStream()); 
     output = new ObjectOutputStream(socket.getOutputStream()); 

     jim = (Mensch) input.readObject(); 
     jim.setAge(33); 

     output.writeObject(jim); 

     input.close(); 
     output.close(); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 

}}

和客戶端:

public class Main { 

public static void main(String[] args) { 
    Mensch jim = new Mensch(19, "Jim"); 

    System.out.println(jim.getAge()); 
    try { 
     Socket s = new Socket("127.0.0.1", 2345); 

     ObjectOutputStream clientOutputStream = new ObjectOutputStream(s.getOutputStream()); 
     ObjectInputStream clientInputStream = new ObjectInputStream(s.getInputStream()); 

     clientOutputStream.writeObject(jim); 



     jim = (Mensch) clientInputStream.readObject(); 

     System.out.println(jim.getAge()); 

     clientOutputStream.close(); 
     clientInputStream.close(); 


    } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
    } catch (UnknownHostException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

}

回答

4

這就是問題所在:

while(true) { 
    ServerSocket s = new ServerSocket(2345); 
    pipe = s.accept(); 
    ... 
} 

你試圖重複地結合到同一個端口。您需要做的只是創建一個單一的ServerSocket並多次呼叫accept。 (我也想移動pipe變量聲明內循環...)

ServerSocket s = new ServerSocket(2345); 
while(true) { 
    Socket pipe = s.accept(); 
    ... 
} 
+0

啊謝謝老兄! – CampingCow

相關問題