Understanding sockets?

Alex Martelli aleax at aleax.it
Tue Mar 25 04:22:21 EST 2003


G wrote:

> Hi Dennis,
> 
> thanks,
> your code works.
> however, it does not work if the client is indefinitely running.
> i would like to have a client that is always running and continually
> sending and receiving messages from the server. i do not know
> how to do this using sockets.

Sockets come in two kinds and neither serves your expressed
purposes directly.  STREAM sockets, the usual kind, have no
concept of "message": an open socket lets you push a stream
of bytes to the counterpart, and/or get some bytes that the
counterpart has pushed onto you, but there is no concept of
any "message boundary" intrinsic in it -- so you'll have to
superimpose such boundaries by layering some higher-level
protocol upon the stream-sockets.  DATAGRAM sockets do have
a concept of "message" -- a finite set of bytes being sent
and received -- *BUT* they do not guarantee sequencing and
reliability -- datagrams may arrive in an order different
from the one in which they were sent, and may even fail to
arrive altogether without any notification to you of that.

So, if you want to build upon datagram sockets, again you
need a higher-level protocol, this time to acknowledge
message receipt and possibly sequencing, resend when an
ack fails to arrive, ignore duplicate copies of the same
msg, etc.  This is much more complicated than just marking
message boundaries, so, in practice, don't do it -- use
datagrams only when reliability and sequencing issues are
livable with.

In practice, you're almost invariably better off looking
for already-existing protocols built on top of stream
sockets and programming to those.  Most often you can
find existing implementations of such protocols in Python,
either in the standard library or freely available for
downloading.  But, to pick the right protocol for your
purposes, such purposes need to be better described than
you have done so far.


Alex





More information about the Python-list mailing list