Page 1 of 1

asyncio.open_connection no exception

Posted: Fri Jul 15, 2022 5:07 pm
by ajvperth
Hello,
I try to check if an TCP port is open on a ESP32 and use following function to achieve this

Code: Select all

import uasyncio as asyncio

# Returns True if port available
async def isPortOpen(ip, port):
    try:
        print('Testing:', ip, port)
        reader, writer = await asyncio.open_connection(ip, port)
        print(reader, writer)
        writer.close()
        return True
    except:
        return False


async def main():
    b = await isPortOpen('127.0.0.1', 5000)
    print (b)
    
    
asyncio.run(main())
On CPython this works fine, on micropython it returns always : Port = open / available
I read about the differences between CPython and micropython:
https://docs.micropython.org/en/latest/ ... index.html
but did not find something fitting and I read the manual:
https://docs.micropython.org/en/latest/ ... ght=reader
it says:
Will raise a socket-specific OSError if the host could not be resolved or if the connection could not be made.

This OSError exception, if it was raised, was not catched in my program while it is catched in CPython.

Can you give some comment on this?
Maybe an other way to check if a port is available on the network?
Thanks

Re: asyncio.open_connection no exception

Posted: Sat Jul 16, 2022 4:31 pm
by ajvperth
I did found a way around by leaving asyncio and replacing it with a blocked mode function, this works as expected:

Code: Select all

# Returns True if port available
def isPortOpen2(ip, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect((ip, port))
        sock.close()
        return True
    except:
        return False
Off-course I prefer an asyncio solution

Re: asyncio.open_connection no exception

Posted: Sun Jul 17, 2022 3:30 pm
by pythoncoder
I'm puzzled. Firstly, if I run your code on a Pico W it returns False:

Code: Select all

=== import uasyncio as asyncio
=== 
=== # Returns True if port available
=== async def isPortOpen(ip, port):
===     try:
===         print('Testing:', ip, port)
===         reader, writer = await asyncio.open_connection(ip, port)
===         print(reader, writer)
===         writer.close()
===         return True
===     except:
===         return False
=== 
=== 
=== async def main():
===     b = await isPortOpen('127.0.0.1', 5000)
===     print (b)
===     
===     
=== asyncio.run(main())
=== 
Testing: 127.0.0.1 5000
False
>>> 
If you look at the source, uasyncio does raise an exception.

Re: asyncio.open_connection no exception

Posted: Sun Jul 17, 2022 3:41 pm
by pythoncoder
The plot thickens.

Your code works on Pico W and Pyboard D.

It does not on ESP32 and ESP8266. I suggest you raise an issue.