我正在通过套接字编程将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;
}发布于 2014-05-19 07:11:51
应用程序在其远程服务崩溃时面临的最大问题是,根本无法预测何时返回(如果有的话)。
您已经在使用TCP连接,当面临短期无法访问的服务时,该连接将重新尝试,但是当TCP声明连接失效时,您实际上不会通过自动重新建立连接来提高可靠性。例如,如果远程服务器返回需要两天的时间,您的应用程序是否能够像从未中断过一样工作呢?所有必要的数据会在中断期间排队吗?在周末的失败过程中,连接系统的语义会保持不变吗?如果远程服务中断5天,情况如何?
从系统的角度来看,您能做的最好的事情就是通知操作符有一个需要注意的错误。正因如此,我们仍有营办商,并会在可预见的将来继续经营。
https://stackoverflow.com/questions/23731226
复制相似问题