我想在我的代码中实现一个处理程序,以允许客户端自动连接到同一网络上服务器的第二个实例,如果连接到此客户端的服务器在 10 秒后没有响应。我做错了什么??
private static void connectToServer(String serverHostname, int port) throws UnknownHostException, IOException
{
try {
echoSocket = new Socket(serverHostname, 10118);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket
.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Not connected to server: "
+ serverHostname);
System.exit(1);
}
}
public static void main(String[] args) throws IOException {
listServer.add("10.196.113.31");
listServer.add("10.196.113.27");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
try {
if (args.length > 0)
serverHostname = args[0];
System.out.println("Trying to connect to host " + serverHostname
+ " at port 10118.");
connectToServer(getServer(), 10118);
echoSocket.setSoTimeout(10000);
String userInput;
System.out.print("Input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (!echoSocket.isConnected()) connectToServer(serverHostname, 10118);
System.out.println("echo: " + in.readLine());
System.out.print("Input: ");
}
} catch (SocketTimeoutException e) {
NextServer();
connectToServer(getServer(), 10118);
System.out.println("Timeout");
// TODO: handle exception
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
private static void NextServer(){
idServer ++;
}
private static String getServer(){
return listServer.get(idServer);
}
编辑
当我运行服务器,然后是客户端时,一切都很好。然后我在同一网络上的另一台机器上启动第二台服务器,并尝试从同一客户端发送文本,客户端应该自动检测到第一台服务器已断开连接,连接到服务器的第二个实例并发送文本消息。这是我得到的例外:
线程"main"java.net.Socket异常:连接重置 at java.net.SocketInputStream.read(Unknown Source) at sun.nio.cs.StreamDecoder.readBytes(未知来源) at sun.nio.cs.StreamDecoder.implRead(未知来源) at sun.nio.cs.StreamDecoder.read(未知来源) at java.io.InputStreamReader.read(Unknown Source) at java.io.BufferedReader.fill(Unknown Source) at java.io.BufferedReader.readLine(Unknown Source) at java.io.BufferedReader.readLine(Unknown Source) at 问题 3.Client.main(Client.java:62)
如果您希望客户端在服务器断开连接时执行某些操作,则需要做的不仅仅是捕获SocketTimeoutException
。如堆栈跟踪所示,断开连接的断开将导致引发泛型SocketException
。你也应该抓住这一点。
换句话说,看起来您只处理从客户端到服务器的初始连接失败的情况;而不是处理现有条件被删除的情况。
如果服务器没有响应connect
,您的setSoTimeout
将无法涵盖这种情况,因此请确保连接建立代码中有超时。写这个:
SocketAddress a = new InetSocketAddress(serverHostname, 10118);
echoSocket = new Socket();
echoSocket.connect(a, 10000);