我有一个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