【发布时间】:2016-10-23 07:31:53
【问题描述】:
我正在使用 python twisted 库,并且正在制作一个服务器来接收数据以对接收到的数据进行一些处理,然后关闭连接。我观察到程序挂在 dataReceived 中而没有打印语句。使用 print 语句,它会通过。想知道打印是否会以某种方式减慢执行速度以避免竞争条件,或者我是否编写了错误?
我的代码如下:
class Stack(Protocol):
def __init__(self, factory):
self.factory = factory
self.bytesremaining = None
self.payload = ""
self.headerseen = False
def dataReceived(self, data):
if self.headerseen == False:
header = unpack('B',data[0])[0]
if header == 128:
self.pop()
return
self.bytesremaining = self.datalength = unpack('B',data[0])[0]
print self.datalength #without this print the execution hangs in the middle.
if len(data) > 1 and (len(self.factory.pushstack) < 100):
self.payload += data[1:]
self.bytesremaining -= len(data) - 1
self.headerseen = True
elif len(self.factory.pushstack) < 100:
self.payload += data
self.bytesremaining -= len(data) - 1
if self.bytesremaining == 0:
self.factory.pushstack.appendleft(self.payload)
retval = pack('B',0)
self.transport.write(retval)
self.transport.loseConnection()
class StackFactory(ServerFactory):
def __init__(self):
self.clients = []
self.pushstack = collections.deque()
self.popstack = collections.deque()
self.clientsmap = {}
def buildProtocol(self, addr):
return Stack(self)
【问题讨论】:
标签: python asynchronous twisted