TcpConnection

Extends NetConnection. Implements a simple Tcp connection. The implementation is straight forward:

  • read events are forwarded to application ReadHandler.
  • there is no handshake involved. (NetConnection allows a handshake over the stream connection. Not talking about TCP handshake which is out of our scope.)
  • connect event is forwarded to application ConnectHandler.

Closing the connection

If the application receives the notification CloseHandler(CLOSE_READ_WRITE), then the underlying connection is completely disconnected. On network error (like connection reset by peer), the application instantly receives CloseHandler(CLOSE_READ_WRITE).

If the application wishes to instantly terminate the connection it may call:

  • ForceClose(): instantly closes the connection, and triggers a back call to CloseHandler(CLOSE_READ_WRITE)

If the application wishes to close the connection gracefully, it may call:

  • FlushAndClose(CLOSE_WRITE): the connection enters FLUSHING state, sends all data from output buffer, then closes only the write half of the connection. The peer:
    • notices the close
    • may send back some data
    • either completely closes it's end or closes it's write half
      The application is notified by ReadHandler while data arrives, and when all data has be read, the CloseHandler(CLOSE_READ_WRITE) is called.
  • FlushAndClose(CLOSE_READ_WRITE): the connection enter FLUSHING state, sends all data from output buffer, the closes the write half of the connection. The peer:
    • notices the close
    • may send back some data
    • either completely closes it's end or closes it's write half
      The application is notified by ReadHandler while data arrives, and when all data has be read, the CloseHandler(CLOSE_READ_WRITE) is called.

If the peer initializes the close procedure, then the application:

  • receives a call to CloseHandler(CLOSE_READ)
  • it may send back data, using the usual Write. However if the peer has completely closed the socket, the connection gets a send error, triggering the instant complete close, which calls CloseHandler(CLOSE_READ_WRITE).
  • it has to call FlushAndClose(CLOSE_WRITE) or FlushAndClose(CLOSE_READ_WRITE)
  • receives CloseHandler(CLOSE_READ_WRITE), when output buffer gets empty.

The graceful closing of a fully established Tcp connection follows the following chain of events:

      Host A                      Host B
   ------------                ------------
executes:
a) close(fd), or
b) shutdown(SHUT_WR)
            ====================>
                              receives RDHUP, and executes
                              c) close(fd), or
                              d) shutdown(SHUT_WR)
            <====================
a) nothing happens
b) receives HUP,
   and executes close(fd)
            ====================>
                              c) nothing happens
                              d) receives HUP,
                                 and executes close(fd)