当TCP服务器尝试接受来自客户端的连接时,出现“未处理的错误”

时间:2013-06-28 18:59:23

标签: python twisted twisted.internet

from twisted.internet.protocol import Factory,Protocol
from twisted.internet import reactor

class ChatServer(Protocol):
    def connectionMade(self):
        print("A Client Has Connected")

factory = Factory()
reactor.listenTCP(80,factory)
print("Chat Server Started")

reactor.run()

上面的代码成功运行。但是当我尝试打开TCP(telnet localhost 80)时。

发生错误:

Unhandled Error
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\twisted\python\log.py", line 69, in callWithContext
    return context.call({ILogContext: newCtx}, func, *args, **kw)
  File "C:\Python27\lib\site-packages\twisted\python\context.py", line 118, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "C:\Python27\lib\site-packages\twisted\python\context.py", line 81, in callWithContext
    return func(*args,**kw)
  File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 150, in _doReadOrWrite
    why = getattr(selectable, method)()
--- <exception caught here> ---
  File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 718, in doRead
    protocol = self.factory.buildProtocol(self._buildAddr(addr))
  File "C:\Python27\lib\site-packages\twisted\internet\protocol.py", line 104, in buildProtocol
    p = self.protocol()
exceptions.TypeError: 'NoneType' object is not callable

如果有人知道解决方案,请帮助我。我刚刚开始扭曲。

1 个答案:

答案 0 :(得分:3)

class ChatServer(Protocol):
    def connectionMade(self):
        print("A Client Has Connected")

factory = Factory()
reactor.listenTCP(80,factory)

此代码中的factoryChatServer之间没有任何关联。尝试插入此行:

factory.protocol = ChatServer

在即将发布的(尚未发布的)Twisted版本中,Factory正在获得一种新的类方法,使这种设置更加容易。使用该版本,这个例子会更短:

class ChatServer(Protocol):
    def connectionMade(self):
        print("A Client Has Connected")

reactor.listenTCP(80, Factory.forProtocol(ChatServer))