我有一个类似这样的方法:(我在android项目中使用此代码)
void flushAndClose(Socket socket,String s1){
if (socket!=null)
try {
OutputStream outputStream=socket.getOutputStream();
PrintStream printStream=new PrintStream(outputStream,true);
printStream.write(s1.getBytes());
printStream.close(); //This only closes outputStream. Am I wrong?
//Error will occur in inner try-catch
//Again try catch to countinue next statement
//Actually I call method twice so I added second try-catch just for trying it with one method.
try {
System.out.println("socket.isClosed() --> "+socket.isClosed());//Returns false
flushAndClose(socket,s1);
}catch (Exception e){
e.printStackTrace();
System.out.println(e.getMessage());//"Socket is closed"
}
} catch (IOException e) {
e.printStackTrace();
}
}
这是来自grepcode.com
的getOutputStream()方法825 public OutputStream getOutputStream() throws IOException {
826 if (isClosed())
827 throw new SocketException("Socket is closed");
828 if (!isConnected())
829 throw new SocketException("Socket is not connected");
830 if (isOutputShutdown())
831 throw new SocketException("Socket output is shutdown");
832 final Socket s = this;
833 OutputStream os = null;
834 try {
835 os = (OutputStream)
836 AccessController.doPrivileged(new PrivilegedExceptionAction() {
837 public Object More ...run() throws IOException {
838 return impl.getOutputStream();
839 }
840 });
841 } catch (java.security.PrivilegedActionException e) {
842 throw (IOException) e.getException();
843 }
844 return os;
845 }
我得到s1值一次不是两次。我知道在finally块中调用此方法printStream.close();
将解决此问题。
但是我无法理解为什么socket.isClosed()
返回 false 然后当我尝试通过socket.getOutputStream();
方法第二次获得OutputStream类的新实例时,即使我使用 NOT 关闭的相同套接字对象,这也会失败。
并且返回消息为SocketException() --> "Socket is closed"
有谁知道它的原因?只有在socket.close();
返回 true
socket.isClosed();
方法后,才尝试使用其他组合