0

So I am creating a socket connection I want to re-initiate every time a particular loop happens, I have tried many ways to close the socket safely so I can reconnect it but the bind keeps failing on the second loop. Can some one please help me properly close the socket so I can re-engage it? thanks

while T==4:
                if H==1:
                    #conn.shutdown(1)
                    #conn.close()
                    
                    time.sleep(3)
                    HOST3 = ''
                    PORT3 = 20127
                    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#socket.AF_INET, socket.SOCK_STREAM
                    print('in41')
                    try:
                            
                            l=s.bind((HOST3, PORT3))
                            print(l)
                    except socket.error as msg:
                        print('Bind failed. ')
                        #sys.exit()
                        continue
                    s.listen(10)
                    conn, addr = s.accept()
                    H=0
                if H==0:
                    data=conn.recv(2420)
                    data2+=data.decode('utf-8')
                    print(conn)
                    if data2.endswith('...'):
                        print(data2)
                        data2=''
                        #H=1
                        continue
                    if data2.endswith('complete.'):
                        print(data2)
                        data2=''
                        H=1
                        
                        conn.shutdown(81)
                        #conn.close()
                        #s.close()
                        #socket.close(81)
                        #socket.close(1)
                        continue
Munix0
  • 1
  • 3
  • Apart from being able to bind to the same address as the closed socket again using SO_REUSEADDR - your overall design seems to be broken. The common design is to create the listener socket, bind it and listen - and then call accept again and again for each new connection. Don't close the listener socket after each connection and open it again. – Steffen Ullrich Nov 11 '22 at 19:42
  • skipping the rebind fixed it, thanks, cant believe i did not try this earlyer – Munix0 Nov 11 '22 at 20:38

0 Answers0