java 与java中的套接字断开连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5793671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
disconnecting from a socket in java
提问by yotamoo
Hi i am building a little p2p program, implementing both the server-side and the client-side. when I lunch the client-side program, first think it does is to connect to each server in its list, send data (about the client-side) and disconnect. The next time the client-side connects to one of these servers it will be recognized.
嗨,我正在构建一个小 p2p 程序,实现服务器端和客户端。当我吃客户端程序时,首先想到它是连接到其列表中的每个服务器,发送数据(关于客户端)并断开连接。下次客户端连接到这些服务器之一时,它将被识别。
My problem - when i tell the client-side to disconnect, i get this exception
我的问题 - 当我告诉客户端断开连接时,我收到此异常
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at oop.ex3.nameserver.NameServerThread.run(NameServerThread.java:24)
to disconnect i just wrote:
断开连接我刚刚写道:
finally {
out.close();
in.close();
socket.close();
}
so, how do i avoid this exception? thanks!
那么,我该如何避免这个异常呢?谢谢!
回答by Liv
The JavaDoc for Socket.close() states clearly:
Socket.close() 的 JavaDoc 明确指出:
Closing this socket will also close the socket's InputStream and OutputStream.
关闭此套接字也将关闭套接字的 InputStream 和 OutputStream。
which will throw the exception since you've already closed them!
这将抛出异常,因为您已经关闭了它们!
回答by Peter Lawrey
When you close the client side, what would you expect to happen on the server side?
当您关闭客户端时,您希望在服务器端发生什么?
To avoid this exception, you need to implement you own readUnsignedShort() method like.
为避免此异常,您需要实现自己的 readUnsignedShort() 方法,例如。
public int readUnsignedShort() {
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
// don't throw new EOFException();
return -1; // EOF marker.
return (ch1 << 8) + (ch2 << 0);
}
回答by giorgiline
Would it be right doing a flush before closing the output streams?:
在关闭输出流之前进行刷新是否正确?:
finally {
//this is the DataOutputStream
if(dout != null){
dout.flush();
dout.close();
}
//and this the OutputStream
if(out != null){
out.flush();
out.close();
}
if (din != null){
din.close();
}
if (in != null){
in.close();
}
if (socket != null){
socket.close();
}
}