Two Pythons talking to each other?

Donn Cave donn at u.washington.edu
Thu Jul 8 13:05:25 EDT 1999


phil at ricochet.net (phil) writes:
| On Thu, 8 Jul 1999 05:30:40 GMT, "Hans Nowak" <ivnowa at hvision.nl>
| wrote:
...
|> So my question is, how does one generally deal with this? Should I 
|> attach a newline (\n) (or maybe another separator character) after 
|> every string? Or are there other ways to guarantee that two commands 
|> will arrive at the other side as two strings?

| The primary protocols are TCP and UDP. UDP is non-connection oriented
| and will deliver a datagram. Sending a packet from one side to the
| other followed by another packet will not coalesce the packets into
| one. However, seems to me that you really want a session oriented
| solution. I suspect that the guys in the sockets group will tell you
| that a TCP connection is a stream, so all bets are off. Sending "hello
| wordl. " followed by sending "hello snailor" might result in receiving
| "hello wordl.hel" and "lo snailor".  The solution is to impose your
| own protocol on top of this using TCP as a delivery mechanism.
| Something as simple as <NL> delimiting  might do it for you. 

May be worth noting that application protocols can be and are also
designed on top of UDP, where among other things they may add some
kind of sequence monitor - datagram delivery isn't guaranteed, a
datagram may be discarded if its system buffer has filled up.

An alternative to separator data is a byte count prefix.  E.g.,

    def wpacket(self, data):
        count = struct.pack('!l', len(data))
        data = count + data
        while data:
            # write/send isn't guaranteed to send all.
            n = self.write(data)
            data = data[n:]

    def rpacket(self):
        count = self.read(4)
	data = ''
	while len(data) < count:
        	data = data + self.read(struct.unpack('!l', count)[0])
	return data

For later optimization, it might be nice to buffer the data instead of
reading it in little bits, or maybe define a minimum size packet that's
big enough most of the time, which could cut the reads about in half.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list