Skip to main content
 首页 » 编程设计

python之扭曲的框架服务器作为客户端建立连接

2025年05月04日11bluestorm

首先,让我向您展示我的代码及其返回的错误:

print "before import" 
from twisted.internet import protocol #  imports 
print "after protocol" 
from twisted.internet import reactor 
print "after reactor" 
from twisted.internet.endpoints import TCP4ServerEndpoint 
print "after import" 
 
class Echo(protocol.Protocol): 
    """docstring for Echo""" 
    def connectionMade(self): 
        cADDR = self.clnt = self.transport.getPeer().host 
        print "...Connection made with {0}".format(cADDR) 
    def dataReceived(self, data): 
        self.transport.write(data) 
 
class EchoFactory(protocol.Factory): 
    """docstring for EchoFactory""" 
    def buildProtocol(self, addr): 
        return Echo() 
 
 
server = TCP4ServerEndpoint(reactor, 45002) 
server.listen(EchoFactory()) 
reactor.run() 

如您所见,我创建了一些打印语句来准确调试导致问题的导入。现在的错误:

before import 
after protocol 
Traceback (most recent call last): 
  File "C:\Users\Sa'id\Documents\Learning Programming\Python\Core Python Application Programming\Chapter 2 - Network Programming\Twisted\twisted_intro.py", line 9, in <module> 
    from twisted.internet import reactor 
  File "C:\Python27\lib\site-packages\twisted\internet\reactor.py", line 39, in <module> 
    default.install() 
  File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 196, in install 
    reactor = SelectReactor() 
  File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 72, in __init__ 
    posixbase.PosixReactorBase.__init__(self) 
  File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 499, in __init__ 
    self.installWaker() 
  File "C:\Python27\lib\site-packages\twisted\internet\posixbase.py", line 286, in installWaker 
    self.waker = self._wakerFactory(self) 
  File "C:\Python27\lib\site-packages\twisted\internet\posixbase.py", line 81, in __init__ 
    client.connect(server.getsockname()) 
  File "C:\Python27\lib\socket.py", line 224, in meth 
    return getattr(self._sock,name)(*args) 
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it 
>>>  

出于某种原因,我的 Twisted 服务器正在尝试建立连接,而实际上,它应该是在等待连接,而不是建立连接。正如您从错误中看到的那样,它会在 reactor 导入之前打印,但不会在导入之后打印,因此 reactor 确实是这里的问题所在。我已经将它发布在另一个网站上,但没有取得多大成功,但回复者说,这是因为 react 堆试图设置一个 _SocketWaker,但有什么东西阻止了它的设置。他说把你的防火墙关掉就可以了,但是试了之后,还是一样的错误。请注意,我托管此 Echo() 服务器的端口是端口转发的,因此端口可能不是问题所在。任何输入将不胜感激。

谢谢。

请您参考如下方法:

在 UNIX 上,Twisted 使用管道设置线程唤醒程序文件描述符。但是,在 Windows 上,匿名管道在不同的 Windows 版本之间存在一些实现问题和差异,因此它使用套接字对。创建此套接字对涉及连接回本地主机,因此,某些过于激进的防火墙配置可能会触发此区域。