need a thread to keep a socket connection alive?
Serge Orlov
Serge.Orlov at gmail.com
Mon Apr 24 09:25:30 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'
>
>
> 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)
>
>
>
> should i do this with threads? i dont want to interrupt the listening
> cycle to send a ping.
>
> appreciate any tips on how would be the best way to pull this off.
sockobj.settimeout(550)
before the loop and later in the loop:
try:
databack = sockobj.recv(158)
except socket.timeout:
ping_server(sockobj)
continue
Also, as other people pointed out, you'd better make buffered socket
with .makefile() socket method.
More information about the Python-list
mailing list