next up previous contents
Up: CFHT Socket I/O Previous: 3. Client-Side   Contents

A. Internal Server-Side Half-Duplex Buffer Mechanism - sbuf_t

An sbuf_t manages per-client buffer space for socket i/o. It is implemented as a small state machine which has six (6) states, not including the hidden states of being in a read() or write() call. Transitions between the states are triggered in sockserv_run() by the library. There are only two operations done on the sbuf_t:

  1. Send a message to the client. This is done simply by writing directly into the buffer space associated with the sbuf_t, (char*)(sbuf->buffer). This must only be done if the current state is SBUF_EMPTY. In all other states, it is not possible for the server to send a message to the client.

    WARNING: Writing data into the buffer when the state is not SBUF_EMPTY will cause unpredictable results!

  2. Wait for a complete message to be received from a client. When the state becomes SBUF_RECEIVED, a message is waiting in the same buffer which is used to send a message. Once in SBUF_RECEIVED, the caller must do whatever is needed with the data (parse an incoming command as the case might be with a typical socket server.) Before calling sbuf_state() again, the caller must write a response into the same buffer. All received messages must have a response. If the call does no processing at all, this model ends up implementing an echo-server since the received message, still in the buffer, is simply sent back to the client (see the echoserv example).

sockserv_run() essentially calls sbuf_state() in a loop, which makes the state machine run (and makes data go in or out of the socket.) sbuf_state() returns only when a stable or blocking state has been reached. The resulting state is always the return of sbuf_state(), and sockserv_run() uses this in a switch statement to decide what to do next.

While the socket may be able to handle communication in both directions at once, note that this state machine cannot. If there happens to be a partially received message in the buffer when the server wishes to send something out, the receiving message must first come in completely and then be processed, before anything can go out. In this sense, the communication channel is "half-duplex".

This is prototyped in sbuf.h and implemented in sbuf.c. The complete state model is shown in figure 12.

Figure 12: Possible States for an sbuf_t

next up previous contents
Up: CFHT Socket I/O Previous: 3. Client-Side   Contents
Sidik Isani