Twisted dataReceived挂起

时间:2016-10-23 07:31:53

标签: python asynchronous twisted

我正在使用python twisted库并且正在使服务器接收数据以对接收的数据进行一些处理然后关闭连接。我观察到程序在没有print语句的dataReceived中挂起。随着打印声明,它通过。想知道印刷是否会以某种方式减慢执行速度以避免竞争条件或者我编码了错误?

我的代码如下:

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)

1 个答案:

答案 0 :(得分:1)

在我看来,OS X(selectreactor)的默认扭曲反应器不如kqueue稳定。

安装kqueue反应器后,我不再看到这个问题了。

from twisted.internet import kqreactor
kqreactor.install()
from twisted.internet import reactor