【问题标题】:How to write a Twisted client plugin如何编写 Twisted 客户端插件
【发布时间】:2015-06-15 16:24:48
【问题描述】:

我使用twisted 实现了一个客户端。它工作正常。现在我希望能够将命令行参数传递给它,所以我需要实现一个twisted 插件。我已经执行了许多搜索来查找可以显示如何将程序转换为插件的资源。但是我找不到我要找的东西。

这是我client.py代码的相关部分:

import sys
import time
import os
import errno
import re
from stat import *
global runPath

runPath = '/home/a02/Desktop/'

from twisted.python import log
from GlobalVariables import *
from twisted.internet import reactor, threads, endpoints
from time import sleep
from twisted.internet.protocol import ClientFactory# , Protocol
from twisted.protocols import basic
import copy


class MyChat(basic.LineReceiver):
    def connectionMade(self):
        print "Connected to the server!"
        EchoClientFactory.buildClientObject(self.factory, self)
        self.runPythonCommands = RunPythonCommands ()
        return

    def connectionLost(self, reason):
        print "Lost Connection With Server!"
        #self.factory.clients.remove(self)
        #self.transport.loseConnection()
        print 'connection aborted!'
        #reactor.callFromThread(reactor.stop)
        reactor.stop ()
        return

    def lineReceived(self, line):
        #print "received", repr(line)
        line = line.strip ()
        if line == "EOF":
            print "Test Completed"
        self.factory.getLastReceivedMsg (line)
        exeResult = self.runPythonCommands.runPythonCommand(line.strip())

        self.sendLine(exeResult)
        EchoClientFactory.lastReceivedMessage = ""
        EchoClientFactory.clientObject[0].receivedMessages = []
        return

    def message (self, line):
        self.sendLine(line)
        #print line
        return


class EchoClientFactory(ClientFactory):
    protocol = MyChat
    clientObject = []
    lastReceivedMessage = ''

    def buildClientObject (self, newClient):
        client = Client ()
        self.clientObject.append(client)
        self.clientObject[0].objectProtocolInstance = newClient

        return

    def getLastReceivedMsg (self, message):
        self.lastReceivedMessage = message
        self.clientObject [0].lastReceivedMsg = message
        self.clientObject[0].receivedMessages.append (message)
        return 
    def connectionLost (self):
        reactor.stop()
        return

    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason
        connector.connect () 
        return

这是我为我的client_plugin.py 写的:

from zope.interface import implements
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application.internet import TCPServer
from twisted.spread import pb
from slave.client import EchoClientFactory,MyChat, Client, RunPythonCommands, MyError, line


class Options(usage.Options):
    optParameters = [["port", "p", 8789, "The port number to listen on."], ["host", "h", "192.168.47.187", "The host to connect to"]]

class MyServiceMaker(object):
    implements(IServiceMaker, IPlugin)
    tapname = "echoclient"
    description = "Echo Client"
    options = Options

    def makeService(self, options):
        clientfactory = pb.PBServerFactory(EchoClientFactory ())
        return TCPServer(options["host"],int(options["port"]), clientfactory)

serviceMaker = MyServiceMaker()

我使用了文档中提到的相同文件夹层次结构。由于我无法在网络上找到足够的插件示例,我真的被困在这一点上。我将不胜感激任何帮助。谁能告诉我如何更改代码?提前谢谢你。

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    您是否应该使用tac 文件从命令行运行它?

    http://twistedmatrix.com/documents/12.2.0/core/howto/application.html#auto5

    那么在另一个程序中使用你的MyChat 类应该会更容易...

    【讨论】:

    • 我认为您的答案最好放在 cmets 部分。
    【解决方案2】:

    您必须从您的MyServiceMaker().makeService 方法返回一个主要服务对象。尝试添加from twisted.internet import service,然后在makeService 开头添加:top_service = service.Multiservice() 创建 TCPServer 服务:tcp_service = TCPServer(...) 将其添加到顶级服务:tcp_service.setServiceParent(top_service) 然后返回顶级服务:return top_service

    您可能还需要查看来自Dave Peticolas 的优秀系列教程(文章 n°16 对您的问题很有用)

    【讨论】:

    • 能否请您提供详细的解释,而不是您建议的方法的大纲?
    【解决方案3】:

    只需点击此链接获取文档和帮助:

    twistedmatrix - docs

    twisted.readthedocs.io -docs

    from __future__ import print_function
    
    from twisted.internet import reactor
    from twisted.web.client import Agent
    from twisted.web.http_headers import Headers
    
    agent = Agent(reactor)
    
    d = agent.request(
        'GET',
        'http://example.com/',
        Headers({'User-Agent': ['Twisted Web Client Example']}),
        None)
    
    def cbResponse(ignored):
        print('Response received')
    d.addCallback(cbResponse)
    
    def cbShutdown(ignored):
        reactor.stop()
    d.addBoth(cbShutdown)
    
    reactor.run()
    

    输出:

    C:\Python27>python.exe twist001.py
    Response received
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 2015-07-25
      • 2012-04-26
      • 2012-06-01
      • 2015-10-23
      • 1970-01-01
      相关资源
      最近更新 更多