我有一个用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()
答案 0 :(得分:0)
在asyncio中没有ProtocolFactory
抽象接口。只需将Client
或lambda: Client
传递给loop.create_server()