TCP packet size?
Gordon McMillan
gmcm at hypernet.com
Wed Jun 14 08:44:54 EDT 2000
Richard Brodie wrote:
>
>"chris" <chris at rpgarchive.com> wrote in message
>news:3948AC51.98E5EAEC at rpgarchive.com...
>
>>The messages just aren't reassembled the way I thought TCP worked.
>>I'm hoping to find a way to received one message at a time in its
>>entirety, or determine the start and end of my messages
>Everyone programming to the TCP/sockets API gets burnt sooner or later
>by this. Curse three times, dance round the room widdershins, then put
>a data length field in your message header. Check Stevens or any other
>decent introduction to socket prograaming for details.
And use a buffer to reassemble the data into discrete messages, which seems
to be the thing you want to avoid. Here's one pattern you can use (you need
something similar on the write side, too):
def getmsg(self):
if self.buff is None:
raise IOError, "read past end of file"
while 1:
msglen = int(self.buff[:5])
if len(self.buff) > msglen:
msg = self.buff[:msglen]
self.buff = self.buff[msglen:]
return msg
input = self.sock.recv(8192)
if not input:
# socket closed
msg = self.buff
self.buff = None
return msg
self.buff = self.buff + input
- Gordon
More information about the Python-list
mailing list