Open qiwei9743 opened 8 years ago
import asyncio import telnetlib3
async def shell(reader, writer): print("Client connected") writer.write(b"Welcome to the telnet server!\n") async for inp in reader: if inp == b"exit": writer.write(b"Bye.\n") await writer.drain() writer.close() return if inp.strip(): # Check if the input is non-empty response = f"You said: {inp.decode()}\n".encode() writer.write(response) await writer.drain()
loop = asyncio.get_event_loop() server = telnetlib3.create_server( shell=shell, host="127.0.0.1", port=6023, ) server_task = loop.run_until_complete(server)
try: loop.run_forever() except KeyboardInterrupt: pass finally: server_task.close() loop.run_until_complete(server_task.wait_closed()) loop.close()
When I tried the example telnet.py, I found it always echo twice like below. Thank you.
Say something: toggle <= I only typed one 'toggle' You said: toggle Say something: toggle <= I didn't typed this one. You said: toggle
Say something: ffff You said: ffff Say something: ffff You said: ffff
Say something: bbb You said: bbb Say something: bbb Say something: exit Bye. Say something: exit Connection closed by foreign host.