我面临着一个非常不寻常的情况。我有两个通过 HTTP 通信的 Jboss (7.1) 实例。实例 A 打开到实例 B 的 HTTP 连接,并发送一些要处理的数据。连接设置了超时,因此如果 N 秒后没有读取响应,则会抛出 SocketTimeoutEception。执行一些清理并关闭连接。实例 B 有一个 servlet,监听这样的 http 请求,当收到一个请求时,就完成了一些计算。之后,响应被填充并返回给客户端。
问题是如果计算时间过长,客户端(A)会因为超时而关闭连接,但服务器(B)会照常进行,并会在一段时间后尝试发送响应。我希望能够检测到连接已关闭并做一些家务,但我似乎无法做到这一点。
我试过调用 HttpServletResponse.flushBuffer(),但没有抛出异常。我还在http请求中明确设置“连接:关闭”以避免持久连接,但这没有效果。http servlet resonse 正常处理,无一例外地消失在虚空中。我不知道我做错了什么,我在这个网站上读过其他问题,比如:
Java 的 HttpServletResponse 没有 isClientConnected 方法
但在我的情况下它们不起作用。
我认为 jboss servlet 容器可能有一些特定的东西,这会导致忽略或缓冲响应,或者尽管我努力从客户端 (A) 关闭它,但可能重用了 http 连接。如果您能提供一些关于在哪里寻找问题的指示,我会很高兴。我花了几天时间,没有取得相关进展,所以我需要紧急解决这个问题。
以下是相关代码:
客户端代码(服务器 A):
private static int postContent(URL destination, String fileName, InputStream content)
throws IOException, CRPostException
{
HttpURLConnection connection = null;
//Create the connection object
connection = (HttpURLConnection)destination.openConnection();
// Prepare the HTTP headers
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type", "text/xml; charset=UTF-8");
connection.setRequestProperty("Content-Encoding", "zip");
connection.setRequestProperty("Connection", "close");//Try to make it non-persistent
//Timouts
connection.setConnectTimeout(20000);//20 sec timout
connection.setReadTimeout(20000);//20 sec read timeout
// Connect to the remote system
connection.connect();
try
{
//Write something to the output stream
writeContent(connection, fileName, content);
//Handle response from server
return handleResponse(connection);
}
finally
{
try
{
try
{
connection.getInputStream().close();//Try to explicitly close the connection
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.disconnect();//Close the connection??
}
catch (Exception e)
{
logger.warning("Failed to disconnect the HTTP connection");
}
}
}
private static int handleResponse(HttpURLConnection connection)
throws IOException, CRPostException
{
String responseMessage = connection.getResponseMessage();//Where it blocks until server returns the response
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK)
{
logger.debug("HTTP status code OK");
InputStream in = connection.getInputStream();
try
{
if (in != null)
{
//Read the result, parse it and return it
....
}
}
catch (JAXBException e)
{
}
}// if
//return error state
return STATE_REJECTED;
}//handleResponse()
服务器代码(服务器 B):
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String crXML = null;
MediaType mediaType = null;
Object result;
// Get the media type of the received CR XML
try
{
mediaType = getMediaType(request);
crXML = loadDatatoString(mediaType, request);
result = apply(crXML);
}
catch (Exception e)
{
logger.error("Application of uploaded data has failed");
//Return response that error has occured
....
return;
}
// Finally prepare the OK response
buildStatusResponse(response, result);
// Try to detect that the connection is broken
// and the resonse never got to the client
// and do some housekeeping if so
try
{
response.getOutputStream().flush();
response.flushBuffer();
}
catch (Throwable thr)
{
// Exception is never thrown !!!
// I expect to get an IO exception if the connection has timed out on the client
// but this never happens
thr.printStackTrace();
}
}// doPost(..)
public static void buildStatusResponse(HttpServletResponse responseArg, Object result)
{
responseArg.setHeader("Connection", "close");//Try to set non persistent connection on the response too - no effect
responseArg.setStatus(HttpServletResponse.SC_OK);
// write response object
ByteArrayOutputStream respBinaryOut = null;
try
{
respBinaryOut = new ByteArrayOutputStream();
OutputStreamWriter respWriter = new OutputStreamWriter(respBinaryOut, "UTF-8");
JAXBTools.marshalStatusResponse(result, respWriter);
}
catch (Exception e)
{
logger.error("Failed to write the response object", e);
return;
}
try
{
responseArg.setContentType(ICRConstants.HTTP_CONTENTTYPE_XML_UTF8);
responseArg.getOutputStream().write(respBinaryOut.toByteArray());
}
catch (IOException e)
{
logger.error("Failed to write response object in the HTTP response body!", e);
}
}//buildStatusResponse()