Home how to make this code Non-Blocking with Asyncio?
Reply: 0

how to make this code Non-Blocking with Asyncio?

user2297
1#
user2297 Published in May 27, 2018, 3:36 am

I'm trying to create a code that is non-blocking and that allows me to create multiple clients to do some request on a server. However, I can't create more than 1 client simultaneously!

CLIENT.PY

import asyncio

PYTHONASYNCIODEBUG = 1


#ECHO CLIENT PROTOCOL 

async def tcp_echo_client(message, loop):
    # Send request to server
    reader, writer = await asyncio.open_connection('127.0.0.1', 8888, loop=loop)
    print('Send: %r' % message)
    writer.write(message.encode())

    # Receive the information
    if message == '1':
        await asyncio.Task(read_position(reader))
    else:
        await asyncio.ensure_future(read_server(reader))

    # Close the connection
    print('Close the socket')
    writer.close()


#ASYNCIO COROUTINES TO REQUEST INFORMATION 

async def read_server(reader):
    server_message = await reader.read()
    print(type(server_message))
    print('Received: %r' % server_message.decode())


async def read_position(reader):
    while True:
        print("I'm Here")

        server_message = await reader.read(50)
        position = server_message.split()
        print(position)
        print(type(position))
        print('Received: %r' % server_message.decode())


#FUNCTION THAT CREATES THE CLIENT


def main(message):
    '''This function creates the client'''

    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(tcp_echo_client(message, loop))
    finally:
        pass


 # This is how I create a new client

if __name__ == '__main__':
    message = '2'
    main(message)
    message = '3'
    main(message)

I want to create multiples clients, however, the code is blocking in the first main when I send the message('1'). I don't know why the code is blocking if I'm using asyncio. My server accepts multiples connections, because if I run this code seperatly I can do everything. The propose of this is to create clients every time I click a button at my Kivy app to send a request to the server. This problems exists because I want to control a Robot and do a lot of things simultaneously, however with a blocking code I can't do it because I'm get stuck

Maybe it's a stupid question but I've only started coded 2 months ago and I haven't any help.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302981 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO