How are TCP connections closed?
A graceful end to a TCP connection is known as a four-way handshake.
Either the client or server, realizing the connection has fulfilled its purpose, can send a TCP segment with the FIN (final) and ACK (acknowledgment [of the previous segments the other host has already sent]) flags set. According to RFC 793, in the second step, the other host must respond with an ACK segment, regardless of its agreement to end the connection.
If the opposite host agrees the connection has run its course, it then sends its own FIN/ACK segment, which must be answered with an ACK, ending the connection. Alternatively, if the opposite host still has use for the connection, it can simply continue to use it without sending its own FIN/ACK at this time.
Ultimately, the connection ends with a clean four-way handshake that either host can initiate, regardless of which host originally attempted to close the connection.
A later update to the RFC 793 process allowed for a faster three-way tear-down exchange, maintaining the second step in the four-way handshake only for when the opposing host disagrees with ending the connection, indicated by sending the ACK segment previously mentioned. Otherwise, when both hosts are in agreement with ending the connection, the three-way tear-down flow is FIN/ACK from either host, FIN/ACK from the opposite host, and ACK from the originating host.
Another option, if there is a need to immediately end a TCP connection, in effect destroying any chance for both hosts to derive mutual value from it, is that either host can send a segment with only the RST (reset) flag set. No ACK segment should be returned because the sender of the RST considers the connection to be immediately finished and will, therefore, not process the ACK in any way.