大家好!
我在代码(线程)里通过 socket 与另一端通信(先收,然后发,然后再接收,最后关闭)。
但是我发现每次关闭时都会提示这个警告:
跟踪发现是最后的 close 那句执行后出的警告。(为了必要,把这个函数都上传了)
public HTTPResponse post(String host, int port, boolean isKeepAlive)
{
HTTPResponse httpRes = new HTTPResponse();
setHost(host);
setConnection((isKeepAlive == true) ? HTTP.KEEP_ALIVE : HTTP.CLOSE);
boolean isHeaderRequest = isHeadRequest();
OutputStream out = null;
InputStream in = null;
try {
if (postSocket == null){
// Thanks for Hao Hu
postSocket = new Socket();
postSocket.connect(new InetSocketAddress(host, port), HTTPServer.DEFAULT_TIMEOUT);
}
out = postSocket.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(getHeader());
pout.print(HTTP.CRLF);
boolean isChunkedRequest = isChunked();
String content = getContentString();
int contentLength = 0;
if (content != null)
contentLength = content.length();
if (0 < contentLength) {
if (isChunkedRequest == true) {
// Thanks for Lee Peik Feng <pflee@users.sourceforge.net> (07/07/05)
String chunSizeBuf = Long.toHexString(contentLength);
pout.print(chunSizeBuf);
pout.print(HTTP.CRLF);
}
pout.print(content);
if (isChunkedRequest == true)
pout.print(HTTP.CRLF);
}
if (isChunkedRequest == true) {
pout.print("0");
pout.print(HTTP.CRLF);
}
pout.flush();
in = postSocket.getInputStream();
httpRes.set(in, isHeaderRequest);
} catch (SocketException e) {
httpRes.setStatusCode(HTTPStatus.INTERNAL_SERVER_ERROR);
Debug.warning(e);
} catch (IOException e) {
//Socket create but without connection
//TODO Blacklistening the device
httpRes.setStatusCode(HTTPStatus.INTERNAL_SERVER_ERROR);
Debug.warning(e);
} finally {
if (isKeepAlive == false) {
try {
in.close();
} catch (Exception e) {};
if (in != null)
try {
out.close();
} catch (Exception e) {};
if (out != null)
try {
postSocket.close(); // 警告在这里
} catch (Exception e) {};
postSocket = null;
}
}
return httpRes;
}
虽然这个警告不影响使用,但是调试的时候看以这么多东西,总是希望能去掉。请大家帮我看看,是什么原因,怎么改正它?if (out != null)
try {
postSocket.close(); // 警告在这里
} catch (Exception e) {};
改成if(postSocket!=null)试试
貌似楼主的逻辑错误了,你先判断in是否为空,然后把out给close了,然后在判断out是否为空,这样写可以?
------解决方案--------------------------------------------------------