Last active
May 29, 2017 23:37
-
-
Save yingshaoxo/c8b8f992c4a971573937264317173451 to your computer and use it in GitHub Desktop.
asyncio TCP client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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