need a thread to keep a socket connection alive?

Roy Smith roy at panix.com
Mon Apr 24 08:27:03 EDT 2006


nephish at xit.net wrote:

> hey there,
> 
> i have a script that waits for message packets from a data server over
> a socket.
> it goes a little like this:
> 
> while 1:
>         x+=1
>         databack = sockobj.recv(158)
>         if databack:
> 
>                 print 'caught a message %s bytes ' % len(databack)
>                 if len(databack) > 120:
>                         message = databack[3:-3] #strip stx and enx
>                         print '\n\n%s' % message
>         else:
>                break
> print 'end data ack'

You need to go review how TCP works.  All that it guarantees is that you 
will receive bytes in the same order they were sent.  It says nothing about 
maintaining record boundaries.  Just because you did a send(n) at one end, 
it doesn't mean that you can expect to read n bytes in a single recv() call 
at this end.  Multiple send() calls could have their contents accumlated 
into a single recv() call, or a single send() could get broken up into 
several recv() calls.

If you want to read fixed-length messages (as you appear to be trying to do 
with your recv(158)), you need to build a buffering layer which reads from 
the socket into a buffer and then doles out messages to a higher layer from 
that buffer.

> it works fine for a while, but the server requires that i send a
> heartbeat ping every 600 seconds or it will terminate the connection.
> 
> so i also need something like
> while 1:
>      sockobj.send(ping)
>      ping_acknowlage = sockobj.recv(48)
>      time.sleep(550)

This needs to be burried in a lower layer as well.  You want to build some 
kind of bufferedConnection class which hides all this gunk from your 
application.  You probably will want sendMessage() and recvMessage() 
methods for your class.  You probably want to have this class create a 
thread to handle the low-level I/O asyncronously, and put the heatbeat 
processing in there.

This is not a trivial problem.  By the time you're done with it, you will 
have learned a lot about how to communicate over a network.



More information about the Python-list mailing list