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