【发布时间】:2017-02-06 01:59:39
【问题描述】:
我有一个很大的问题,我无法从网上得到答案 python中的套接字。 我正在基于套接字制作一个简单的客户端程序(python): 连接到服务器。
我想做一个功能,它的目的只是尝试连接到服务器,否则应用程序将无法工作。 因为我在整个类中都遇到了“全局”套接字变量的问题,所以我决定在我的 main 中创建一个本地套接字变量并将它传递给所有函数。
我想确保我 100% 理解它: 我是否应该从尝试连接到服务器的函数中返回套接字(否则每秒休眠 0.5 秒并重试) 或者我根本不需要返回套接字,套接字变量本身会被更新?
更新
#will try to connect to the server
def try_connecting_to_server(socket_to_server):
connected = False
while not connected:
try:
socket_to_server.connect((HOST, PORT)) # connect to the server
connected = True
except:
print "couldn't connect to server, sleeping for 0.5 seconds"
time.sleep(0.5)
return socket_to_server
def main():
# start the socket to the server
socket_to_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # setup the socket for future use
try:
socket_to_server = try_connecting_to_server(socket_to_server)
handle_missions(socket_to_server) # pass the socket
except:
print "encountered an error"
finally:
socket_to_server.sendall(PROTOCOL_CLOSE_KEY)
socket_to_server.close()
if __name__ == "__main__":
main()
【问题讨论】:
-
显示您询问的代码会更容易提供帮助,您不觉得吗?
-
@JonathonReinhart ,抱歉,现在更新我的帖子。
-
只执行一个函数的函数是没用的——你可以直接在
main中使用socket_to_server.connect() -
@furas ,我的意思是 try_connecting_to_server 函数将是一个循环,直到客户端连接。