Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

tcp

sockets

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?

like image 783
Shayan Avatar asked Jan 29 '10 22:01

Shayan


People also ask

Can a socket be both client and server?

A socket supports two-way communication between a client and a server, using a well-established protocol. The protocol simply prescribes rules and behavior that both the server and client must follow in order to establish two-way communication.

How do I close connection between server and client?

If you want the server to close the connection, you should use shutdown(cfd, SHUT_RDWR) and close(cfd) after, NOT close(lfd) . This lets the lfd socket open, allowing the server to wait at the accept for the next incoming connection. The lfd should close at the termination of the server.

How do you stop a socket in Java?

Java Socket close() methodThe close() method of Java Socket class closes the specified socket. Once the socket has been closed, it is not available for further networking use. If the socket has a channel, the channel is also closed.

Do you have to close socket?

If the socket is a TCP socket and it is connected, then the TCP connection will not be closed unless the socket is closed or shutdown() is called. Therefore, in this case, you should at least make sure to call shutdown() if you can't close the socket.


1 Answers

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.

like image 168
Nikolai Fetissov Avatar answered Sep 20 '22 00:09

Nikolai Fetissov