[英]How can I know client send FIN package in socket?
In client, when call clent.close()
, it will send a FIN packet to try to end the connection. 在客户端中,当调用
clent.close()
,它将发送FIN数据包以尝试终止连接。 Are there any API for server side to know there comes a FIN packet to close the connection in server side? 服务器端是否有任何API知道有FIN数据包来关闭服务器端的连接? If not, why?
如果没有,为什么? What's the best pratice to close connection in both side?
在双方之间建立紧密联系的最佳实践是什么?
Client code: 客户代码:
String host = "127.0.0.1";
int port = 8899;
Socket client = new Socket(host, port);
String data = "Hello world";
Writer writer = new OutputStreamWriter(client.getOutputStream());
writer.write(data);
writer.flush();
writer.close();
client.close();
When the server receives a FIN, it will treat this as the end-of-stream condition. 服务器收到FIN时,会将其视为流结束条件。
In other words, every time you call read
on the socket's InputStream, it will return -1 instead of reading any data - the same as if you were reading from a file and you got to the end of the file. 换句话说,每次在套接字的InputStream上调用
read
时,它将返回-1而不是读取任何数据-就像您从文件中读取文件一样,直到到达文件末尾。
When the peer receives a FIN: 当对等方收到FIN时:
read()
will return -1 read()
将返回-1 readLine()
will return null readLine()
将返回null readXXX()
will throw EOFException
for any other X. readXXX()
将为任何其他X抛出EOFException
。 What won't happen: 不会发生什么:
Socket.isClosed()
won't magically become true Socket.isClosed()
不会神奇地成为现实 Socket.isConnected()
won't magically become false. Socket.isConnected()
不会神奇地变为假。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.