如何编写一个Twisted客户端插件

34

我已经使用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()

我已经使用了文档中提到的相同文件夹层次结构。由于我在网上找不到足够的插件示例,所以我现在真的卡住了。我会感激任何帮助。请问有人能告诉我如何更改代码吗?谢谢您提前。

3个回答

1

我认为你的回答最好放在评论区,这是我的观点。 - user4396006

0

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

twistedmatrix - 文档

twisted.readthedocs.io -文档

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

0

你需要从你的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的这个优秀系列教程(第16篇文章对你的问题有用)。


请您提供详细的解释,而不是一个简要概述您建议的方法? - user4396006

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接