简体   繁体   中英

Java socket TCP teardown

After I have created a socket and established a connection I use BufferedReader and PrintWriter to write/read from the socket.

Socket s = new Socket(ip, port);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());

When I'm done using the socket I close it.

s.close();

This will cause a TCP fin to be sent and leave a half-open TCP connection. Is there any way to detect if a client/server closed it's end of the connection?

This will cause a TCP fin to be sent and leave a half-open TCP connection.

Not quite. It will leave a half-open TCP connection that will issue resets if it receives any more data.

Is there any way to detect if a client/server closed its end of the connection?

Not if you've already closed yours. If you had just issued a write shutdown, you could read until EOS, which would tell you about the peer close, then close the socket. Not much point really unless you really have to achieve simultaneous closes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM