【发布时间】:2016-04-21 19:22:11
【问题描述】:
我有一个名为startServerConnection() 的void 方法,它将服务器连接到一个端口,在本例中为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(),那么客户端一定会遇到异常。它是什么?注意,您不会通过注释掉唯一可以告诉您的代码来找出答案。并且不要破坏您自己的帖子。
标签: java sockets server serversocket