2016-04-21 95 views
-1

我有一個void方法,稱爲startServerConnection(),將服務器連接到端口,在本例中爲7777.此方法在另一個類的按鈕ClientGUI的動作偵聽器中調用。服務器未連接

我敢肯定的代碼是正確的,但由於某種原因,我得到的唯一輸出是"Waiting for connection..."

public void startServerConnection(){ 
     try{ 
      serverSocket = new ServerSocket(portNumber); 

      while(true){ 
       System.out.println("Waiting for a connection..."); 
       Socket clientSocket = serverSocket.accept(); 
       System.out.println("Connection established on port: "+clientSocket.getLocalPort()); 
       ClientConnection clientConnection = new ClientConnection(clientSocket); 
       Thread thread = new Thread(clientConnection); 
       thread.start(); 
      } 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
      return; 
     } 
    } 

編輯 客戶端類,connectClient方法:

public void connectClient(String user){ 
     try{ 
      host = clientSocket.getInetAddress(); 
      clientSocket = new Socket(host,port); 
      new ClientHandler(clientSocket).run(); 
      String accepted = "Connection for host "+host+" accepted on port: "+clientSocket.getPort(); 
     } 
     catch(Exception e){ 
      //sendMessage("Connection error: "+e); 
      //serverGUI.appendEventsLog("Client "+new ClientGUI(username, port)+" failed to connect"); 
     } 

    } 

任何有什麼問題的想法?

+0

服務器無法連接。客戶連接;服務器接受。如果你的服務器永遠不會接受'accept()',客戶端必須得到一個異常。它是什麼?注意你不會通過評論可以告訴你的唯一代碼來找出答案。並且不要破壞你自己的帖子。 – EJP

回答

1

更新:

public void connectClient(String user){ 
    try{ 
     clientSocket = new Socket(host,port); 
     // Use PrintWriter to send data out to server 
     // Use BufferedReader to receive data from server 
    } 
    catch(Exception e){ 
     //sendMessage("Connection error: "+e); 
     //serverGUI.appendEventsLog("Client "+new ClientGUI(username, port)+" failed to connect"); 
    } 
} 

主機的IP地址或主機名,如果服務器/客戶端在同一臺機器上運行,您可以使用「127.0.0.1」或「localhost」的;端口是int一個值,你的情況是7777

原文:

accept()是阻塞函數。之後的代碼將不會徹底,直到連接建立。

你必須建立連接的客戶端和請求,一旦服務器和客戶端的連接,你會看到「端口上建立的連接。」

公共插座接受()拋出IOException異常

偵聽與此套接字的連接並接受它。該方法會阻塞,直到建立連接。

+0

請檢查編輯 – Guest

+0

是的,我也正在閱讀你剛發給我的鏈接。寫消息我會在另一個處理每個客戶端實例的類中完成。我努力瞭解'host'。這應該是一個用戶名或IP地址? – Guest

+0

我認爲主機是IP地址,因此host.getInetAddress()並將其傳遞到套接字。 – Guest