How much data waiting in a socket?
James H. Coombs
JAZBO%BROWNVM.BITNET at mitvma.mit.edu
Mon Dec 19 12:43:05 AEST 1988
>From: Chris Newcomb <newcomb at cory.berkeley.edu>
>Date: 11 Dec 88 11:10:35 GMT
>I'm writing a server that communicates with clients over SOCK_STREAM
>connections. (4.3 BSD) All requests to, and responses from, the server are
>text commands, such as "MODE PRIV" and "ADD fred". When the server reads a
>command from a client's connection, how does it know how many bytes to read,
>since commands will be of variable (and indeterminate) length?
1. For typed data, consider using type-specific functions. These functions
should use the htonl/ntohl macros (e.g., for longs) to ensure that the
client and the server get the data in the right byte order. (That's
host-to-network-long and network-to-host-long---in sys/netinet/inet.h)
(You may need only strings for this application, but as a general
principle; also, I would use op codes instead of, e.g., ADD--send a single
char and eliminate parsing commands out in the server.)
2. For strings, I use a two-byte length prefix.
3. For untyped data, such as structures, I use a two-byte length prefix.
The client and server must then perform network conversions themselves.
This technique guarantees that a recv does not read the contents of two
sends. The server and client must still be synchronized.
--Jim
Dr. James H. Coombs
Software Engineer, Research
Institute for Research in Information and Scholarship (IRIS)
Brown University
jazbo at brownvm.bitnet
Acknowledge-To: <JAZBO at BROWNVM>
More information about the Comp.unix.questions
mailing list