new sockets for old?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
KJM
Posts: 158
Joined: Sun Nov 18, 2018 10:53 pm
Location: Sydney AU

new sockets for old?

Post by KJM » Fri Sep 02, 2022 12:25 am

I've got

Code: Select all

s=socket.socket(); s.connect(ai); s=ssl.wrap_socket(s, server_hostname=host)
as part of a loop that does DNS lookup etc. If I get an [Errno 128] ENOTCONN (socket not connected) the exception code closes the socket & returns to the loop for another try. However on the next pass through the loop, after the closure of the previous socket, I get [Errno 9] EBADF (calling connect on previously closed socket). I don't understand why this happening on a new socket? I tried a time.sleep(1) after closing the disconnected socket but it hasn't helped. What am I missing?

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: new sockets for old?

Post by jimmo » Fri Sep 02, 2022 7:31 am

Need to see the whole code, including the loop.

KJM
Posts: 158
Joined: Sun Nov 18, 2018 10:53 pm
Location: Sydney AU

Re: new sockets for old?

Post by KJM » Sat Sep 03, 2022 3:43 am

Code: Select all

def _request(method, url, data=None):
   proto, dummy, host, path=url.split("/", 3); s=0
   for i in range(2):
     try:
       ai=(ipa, 443) 
       s=socket.socket(); s.connect(ai); s=ssl.wrap_socket(s, server_hostname=host)
       s.write(b"%s /%s HTTP/1.0\r\nHost: %s\r\n" % (method, path, host))
       if data: s.write(b"Content-Length: %d\r\n" % len(data))
       s.write(b"\r\n")
       if data: s.write(data)
       l=s.readline(); l=l.split(None, 2); status=int(l[1]); reason = ""
       if len(l)>2: reason=l[2].rstrip()
       while 1:
         l=s.readline()
         if not l or l==b"\r\n": break
    except OSError as e:
       if s: print('close socket'); s.close()                   # eg  [Errno 128] ENOTCONN

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: new sockets for old?

Post by jimmo » Sat Sep 03, 2022 1:07 pm

KJM wrote:
Fri Sep 02, 2022 12:25 am
I get [Errno 9] EBADF (calling connect on previously closed socket).
Which port and board are you using? Which MicroPython version?

Is that the exact code you're using? The "ipa" variable is never set.

Post Reply