我想在我的代码中实现一个处理程序,以允许客户端自动连接到同一网络上的服务器的第二个实例,如果连接到该客户端的服务器在 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);
}
编辑
当我运行服务器,然后是客户端时,一切都很好。然后我在同一网络的另一台机器上启动第二个服务器,并尝试从同一个客户端发送文本,客户端应该自动检测到第一个服务器断开连接,连接到服务器的第二个实例并发送文本消息。这是我得到的例外:
线程“主”java.net.SocketException 中的异常:在 sun.nio.cs.StreamDecoder.readBytes(Unknown Source) at sun.nio.cs.StreamDecoder.implRead 的 java.net.SocketInputStream.read(Unknown Source) 处的连接重置(Unknown Source) at sun.nio.cs.StreamDecoder.read(Unknown Source) 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 Q3.Client.main(Client.java:62)