Listing 1: Parsing AL messages from a TCP byte stream.
#define MAX_MSG 100 /* maximum length of a message */ #define TERM_CHAR '@' /* message termination character */ #define NULL_CHAR 0x00 int errno; int read_msg (fd, bp) int fd; char *bp; { static char stream_buffer [MAX_MSG + ]; static char * sbp = stream_buffer; static int rcnt = 0; int rc, i; char *cp; errno = 0; while (1) { if (rcnt > 0) { cp = strchr (stream_buffer, TERM_CHAR); if (cp != NULL_CHAR) { i = (cp - stream_buffer); strncpy (bp, stream_buffer, i); rcnt = rcnt - i - 1; if (rcnt > 0) { strncpy (stream_buffer, &stream_buffer [i+1], rcnt); stream_buffer [rcnt] = NULL_CHAR; } return (i); } } if (rcnt >= MAX_MSG) break; rc = recv (fd, &stream_buffer [rcnt], MAX_MSG - rcnt, 0); stream_buffer [rcnt + rc] = 0x0; if (rc < 0) { *bp = NULL_CHAR; rcnt = 0; return (-1); } else if (rc == 0) { *bp = NULL_CHAR; rcnt = 0; errno = 0; return (0); } else rcnt += rc; } *bp = NULL_CHAR; rcnt = 0; errno = 0; return (-1); }