如何继续尝试在Python中建立连接

时间:2016-06-28 19:09:03

标签: python sockets networking

如果我尝试运行以下代码时服务器未启动,我只会收到连接拒绝错误。

如何让下面的发送者继续尝试建立连接,并可能发送直到远程服务器确实启动并且连接成功建立?

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 个答案:

答案 0 :(得分: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