2016-06-28 150 views
0

如果在嘗試運行以下代碼時服務器未啓動,我只是收到Connection refused錯誤。如何繼續嘗試在Python中建立連接

如何讓發件人在下面繼續嘗試建立連接,並可能發送,直到遠程服務器確實啓動並且連接成功建立?

HOST = client_ip # The remote host 
    PORT = port   
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    s.connect((HOST, PORT)) 
    s.sendall(msg) 

    if expect_receive: 
     received_data = s.recv(1024) 
     print received_data 
     #client has started 

    s.close() 
    return 

回答

1

蠻力怎麼樣?像這樣的東西

import time 
while 1: 
    HOST = client_ip # The remote host 
    PORT = port  
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    try: 
     s.connect((HOST, PORT)) 
    except: 
     print("FAILED. Sleep briefly & try again") 
     time.sleep(10) 
     continue 
    s.sendall(msg) 

    if expect_receive: 
     received_data = s.recv(1024) 
     print received_data 
     #client has started 

    s.close() 
    return 
+0

絕對的輝煌!謝謝! – Jobs