我有一个简单的扭曲客户端,它连接到扭曲的服务器并查询索引。如果您看到FN。 connectionMade()class SpellClient, , 这 query 用硬编码。是否是为了测试目的。一个人将如何从外部通过此班级?

编码 -

from twisted.internet import reactor
from twisted.internet import protocol

# a client protocol
class SpellClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""

    def connectionMade(self):
        query = 'abased'
        self.transport.write(query)

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        print "Server said:", data
        self.transport.loseConnection()

    def connectionLost(self, reason):
        print "connection lost"

class SpellFactory(protocol.ClientFactory):
    protocol = SpellClient

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()

# this connects the protocol to a server runing on port 8000
def main():
    f = SpellFactory()
    reactor.connectTCP("localhost", 8090, f)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()
有帮助吗?

解决方案

协议,例如SpellClient,可以作为Self.Factory访问其工厂。
...因此,将有多种方法可以做到这一点,但是一种方法是在Spellfactory上创建另一种方法,例如SetQuery,然后从客户端访问该方法...

#...in SpellFactory:  
def setQuery(self, query):
    self.query = query


#...and in SpellClient:
def connectionMade(self):
    self.transport.write(self.factory.query)

...所以主要:

f = SpellFactory()
f.setQuery('some query')
...

...或者您可以创建一个_在里面_拼写方法的方法,然后将其传递到那里。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top