Skip to content

Instantly share code, notes, and snippets.

@yingshaoxo
Last active May 29, 2017 23:37
Show Gist options
  • Save yingshaoxo/c8b8f992c4a971573937264317173451 to your computer and use it in GitHub Desktop.
Save yingshaoxo/c8b8f992c4a971573937264317173451 to your computer and use it in GitHub Desktop.
asyncio TCP client
import asyncio
import threading
class EchoClientProtocol(asyncio.Protocol):
def __init__(self, message, loop):
self.message = message
self.loop = loop
def connection_made(self, transport):
transport.write(self.message.encode())
print('Data sent: {!r}'.format(self.message))
def data_received(self, data):
print('Data received: {!r}'.format(data.decode()))
def connection_lost(self, exc):
print('The server closed the connection')
print('Stop the event loop')
self.loop.stop()
loop = asyncio.get_event_loop()
message = 'Hello World!'
coro = loop.create_connection(lambda: EchoClientProtocol(message, loop),
'127.0.0.1', 8888)
transport, protocol = loop.run_until_complete(coro) # Only first time return 'transport' and 'protocol'
threading.Thread(target=loop.run_forever).start() # Just make it running.
while True:
transport.write(input("say something: ").encode("utf-8"))
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment