Is it possible to close Java sockets on both client and server sides?

前端 未结 5 855
灰色年华
灰色年华 2021-01-02 17:09

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

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 17:23

    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.

    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.

    Hope this helps.

提交回复
热议问题