Python 2 有一个带有 asyncore.dispatcher 的实现类 我需要在 Python 3 中实现相同的功能。
class Server(asyncore.dispatcher):
def __init__(self, host, port, socketMap=None):
asyncore.dispatcher.__init__(self, None, *socketMap*)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
def handle_accept(self):
sock, addr = self.accept()
handler = Handler(self, sock, self._map)
def run(self):
while True:
asyncore.loop(0.001, True, self._map, 1)
self.handle_close()
class Handler(asyncore.dispatcher):
def __init__(self, server, sock, socketMap):
self._server = server
asyncore.dispatcher.__init__(self, sock, socketMap)
def handle_read(self):
buf = self.recv(8192)
print(buf)
def handle_write(self):
sent = self.send("hello")
也许有实施示例或者他们可以告诉我从哪里开始 我试着写
async def echo(connection: socket,
loop: AbstractEventLoop) -> None:
while data := await loop.sock_recv(connection, 1024):
await loop.sock_sendall(connection, data)
async def listen_for_connection(server_socket: socket,
loop: AbstractEventLoop):
while True:
connection, address = await loop.sock_accept(server_socket)
connection.setblocking(False)
print(f"Got a connection from {address}")
asyncio.create_task(echo(connection, loop))
async def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8000)
server_socket.setblocking(False)
server_socket.bind(server_address)
server_socket.listen()
await listen_for_connection(server_socket, asyncio.get_event_loop())
asyncio.run(main())
我现在不知道如何创建与服务器类似的类(asyncore.dispatcher)
要启动一个简单的异步回显服务器来侦听某个地址/端口,您可以使用以下示例:
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info("peername")
print(f"Received {message} from {addr}")
print(f"Send: {message}")
writer.write(data)
await writer.drain()
print("Closing the connection")
writer.close()
async def main():
server = await asyncio.start_server(handle_echo, "127.0.0.1", 5000)
addr = server.sockets[0].getsockname()
print(f"Serving on {addr}")
async with server:
await server.serve_forever()
asyncio.run(main())
运行代码将启动服务器。在另一个终端中,您可以键入以下命令:
$ echo "Hello World" | curl telnet://127.0.0.1:5000
服务器将响应
Hello World