是否可以在客户端和服务器端都关闭Java套接字? [英] Is it possible to close Java sockets on both client and server sides?

查看:46
本文介绍了是否可以在客户端和服务器端都关闭Java套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个Java应用程序之间建立了套接字TCP连接.当一侧关闭插槽时,另一侧保持打开状态.但我希望将其关闭.而且我也迫不及待地想看看它是否可用,然后关闭它.我想要某种方式从一侧完全关闭它.我该怎么办?

I have a socket tcp connection between two java applications. When one side closes the socket the other side remains open. but I want it to be closed. And also I can't wait on it to see whether it is available or not and after that close it. I want some way to close it completely from one side. What can I do?

推荐答案

TCP不能像这样工作.操作系统将不会释放资源,即文件描述符和端口,直到应用程序显式关闭套接字或死掉,即使TCP堆栈知道另一端已将其关闭.从对等方收到FIN时,从内核到用户应用程序之间没有回调.操作系统将其确认给另一端,但在发送FIN数据包之前等待应用程序调用 close().看看 TCP状态转换图-您处于被动关闭框中.

TCP doesn't work like this. The OS won't release the resources, namely the file descriptor and thus the port, until the application explicitly closes the socket or dies, even if the TCP stack knows that the other side closed it. There's no callback from kernel to user application on receipt of the FIN from the peer. The OS acknowledges it to the other side but waits for the application to call close() before sending its FIN packet. Take a look at the TCP state transition diagram - you are in the passive close box.

一种检测这种情况而不将线程专用于每个套接字的方法是使用 select/poll/epoll/kqueue 系列函数.被动关闭的套接字将被标记为可读,并且尝试读取将返回EOF.

One way to detect a situation like this without dedicating a thread to each socket is to use the select/poll/epoll/kqueue family of functions. The socket being passively closed will be signaled as readable and read attempt will return the EOF.

希望这会有所帮助.

这篇关于是否可以在客户端和服务器端都关闭Java套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆