我通过套接字编程将xml数据发送到服务器。我发现有时当服务器关闭并且客户端报告套接字超时时,我无法发送或接收。
我想处理此异常并尝试重新发送3到4次。我应该使用Thread.sleep,写入循环,还是有更好的方法?
private String sendRequestToChannel(String request) {
String xmlData = null;
BufferedReader rd = null;
BufferedWriter bw = null;
String line = null;
String lineSep = null;
String data = null;
StringBuffer serverData = null;
try {
Socket cliSocket = new Socket();
cliSocket.connect(new InetSocketAddress(HOST, PORT), SOCKET_TIMEOUT);
bw = new BufferedWriter(new OutputStreamWriter(cliSocket.getOutputStream()));
bw.write("POST " + PATH + " HTTP/1.0\r\n");
bw.write("Host: " + HOST + "\r\n");
bw.write("Content-Length: " + request.length() + "\r\n");
bw.write("Pragma: cache\r\n");
bw.write("Cache-Control: private, must-revalidate\r\n");
bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
bw.write("\r\n");
bw.write(request);
bw.flush();
rd = new BufferedReader(new InputStreamReader(cliSocket.getInputStream()));
System.out.println("Step 4 : Getting Input Stream");
serverData = new StringBuffer("");
lineSep = System.getProperty("line.separator");
while ((line = rd.readLine()) != null) {
serverData.append(line);
serverData.append(lineSep);
}
data = serverData.toString();
int index = data.indexOf("<");
if (index != -1) {
xmlData = data.substring(index);
} else {
System.out.println("\r\n \r\n XML Data Not Retrived");
}
} catch (java.net.UnknownHostException uh) {
uh.printStackTrace();
System.out.println("$$$$$$$$$$$$ in sendRequestToChannel : UnknownHostException " + uh.getMessage());
return " in sendRequestToChannel : UnknownHostException " + uh.toString();
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("$$$$$$$$$$$$ in sendRequestToChannel : IOException " + ioe.getMessage());
return " in sendRequestToChannel : IOException " + ioe.toString();
} catch (Exception e) {
e.printStackTrace();
System.out.println("$$$$$$$$$$$$ in sendRequestToChannel : Exception " + e.getMessage());
return " in sendRequestToChannel : Exception " + e.toString();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException ex) {
Logger.getLogger(SA_Caesar.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (rd != null) {
rd.close();
}
} catch (IOException ex) {
Logger.getLogger(SA_Caesar.class.getName()).log(Level.SEVERE, null, ex);
}
bw = null;
rd = null;
line = null;
lineSep = null;
data = null;
serverData = null;
}
return xmlData;
}
答案 0 :(得分:0)
当远程服务出现故障时,应用程序面临的最大问题是,根本没有可以预测何时返回
。您已经在使用TCP连接,在面对短期无法访问的服务时会重试,但是当TCP宣布连接失效时,您实际上并没有通过自动尝试重新建立连接来提高可靠性连接。例如,如果远程服务器需要两天时间才能返回,那么您的应用程序是否能够像从未停止过一样行事?在停电期间,所有必要的数据是否都会排队?连接系统的语义是否会在周末的故障中得到保留?如果远程服务停机5天怎么样?
从系统角度来看,您可以做的最好的事情是通知操作员有一个需要注意的故障。这就是我们在可预见的未来仍然拥有运营商和意愿的原因。