Page 1 of 1

new sockets for old?

Posted: Fri Sep 02, 2022 12:25 am
by KJM
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?

Re: new sockets for old?

Posted: Fri Sep 02, 2022 7:31 am
by jimmo
Need to see the whole code, including the loop.

Re: new sockets for old?

Posted: Sat Sep 03, 2022 3:43 am
by KJM

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

Re: new sockets for old?

Posted: Sat Sep 03, 2022 1:07 pm
by jimmo
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.