将Twisted代码转换为Asyncio代码

时间:2018-02-17 07:42:27

标签: python python-3.x python-2.7 twisted python-asyncio

我有一个用Twisted编写的代码,我将它转换为Asyncio时遇到了麻烦。从我的问题来看,问题是关于Server类中的协议。用Twisted编写的代码是:

from twisted.internet import reactor, protocol
class Client():
    def __init__(self):
        self.something = ""

    def dataReceived(self, packet):
        print(packet)

    def makeConnection(self, transport):
        self.transport = transport
        self.server = self.factory

    def connectionLost(self, args):
        print("Connection lost.")

class Server(protocol.ServerFactory):
    protocol = Client

if __name__ == '__main__':
    validPort = []
    S = Server()
    try:
        reactor.listenTCP(44444, S)
        validPort.append(44444)
    except:
        print('Problem about port.')

    if not validPort == []:
        print('Server is running.')
    reactor.run()

这是我转换为Asyncio并且不起作用的代码(我不确定问题是关于Server Class中的协议):

import asyncio, logging, sys
SERVER_ADDRESS = ('localhost', 44444)

logging.basicConfig(
    level=logging.DEBUG,
    format='%(name)s: %(message)s',
    stream=sys.stderr,
)
log = logging.getLogger('main')

event_loop = asyncio.get_event_loop()

class Client():
    def __init__(self):
        self.something = ""

    def data_received(self, packet):
        self.log.debug('received {!r}'.format(data))
        print(packet)

    def connection_made(self, transport):
        self.transport = transport
        self.server = self.factory
        self.log = logging.getLogger(
            'EchoServer_{}_{}'.format(*self.address)
        )
        self.log.debug('connection accepted')

    def connection_lost(self, args):
        if error:
            self.log.error('ERROR: {}'.format(error))
        else:
            self.log.debug('closing')
        super().connection_lost(error)

class Server(asyncio.Protocol):
    protocol = Client

if __name__ == '__main__':
    S = Server()
    factory = event_loop.create_server(S, *SERVER_ADDRESS)
    server = event_loop.run_until_complete(factory)
    log.debug('starting up on {} port {}'.format(*SERVER_ADDRESS))
    try:
        event_loop.run_forever()
    finally:
        log.debug('closing server')
        server.close()
        event_loop.run_until_complete(server.wait_closed())
        log.debug('closing event loop')
        event_loop.close()

1 个答案:

答案 0 :(得分:0)

在asyncio中没有ProtocolFactory抽象接口。只需将Clientlambda: Client传递给loop.create_server()

即可