本文介绍了需要一个线程来保持套接字连接活着吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿那里,


i有一个脚本等待来自数据服务器的消息包通过

a socket。

it有点像这样:


而1:

x + = 1

databack = sockobj.recv(158)

如果databack:


print''捕获了一条消息%s bytes''%len(databack)

if len(databack) > 120:

message = databack [3:-3] #strip stx和enx

print''\ n \ n%s''%message

其他:

休息

打印''结束数据确认''

它工作正常一段时间,但服务器要求我每隔600秒发送一次

心跳ping,否则它将终止连接。


所以我还需要类似
$ b $的东西b而1:

sockobj.send(ping)

ping_acknowlage = sockobj.recv(48)

time.sleep(550)


我应该用线程吗?我不想打断聆听

周期发送ping。


感谢任何有关如何将其解决的最佳方法的提示。 />

解决方案




如果这是一个带有会话协议的TCP连接,你就不能拥有

两个线程读取套接字的字节,没有某种

协调。当一个线程解析它收到的字节时,一些字节可能会成为另一个线程的下一条消息的一部分。


你可能会更好地使用异步I / O和状态机模型。





-
$ b $bRenéPijlman






可能是值得在必要时重新连接。毕竟,你也可以出于其他原因断开



-

Ben Sizer


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.

解决方案



If this is a TCP connection with a conversational protocol, you can''t have
two threads reading bytes of the socket, without some sort of
coordination. When one thread parses the bytes it received, some bytes may
be part of the next message for the other thread.

You may be better off with asynchronous I/O and a state machine model.
http://squirl.nightmare.com/medusa/async_sockets.html
http://www.python.org/doc/lib/module-asyncore.html
http://twistedmatrix.com/projects/co...o/clients.html

--
René Pijlman





It is probably worth just reconnecting if necessary. After all, you
could be disconnected for other reasons too.

--
Ben Sizer


这篇关于需要一个线程来保持套接字连接活着吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 12:45