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

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

问题描述

我在两个 java 应用程序之间有一个 socket 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天全站免登陆