我有一个大问题我无法从网上得到答案 python中的套接字。 我正在制作一个基于socket的简单客户端程序(python): 正在连接到服务器。在
我想做一个函数,它的目的只是试图连接到服务器,否则应用程序将无法工作。 因为在整个类中使用“global”套接字变量时遇到了问题,所以我决定在main中创建一个局部套接字变量,并将其传递给所有函数。在
我想确保我百分之百地理解它: 我是否应该从试图连接到服务器的函数中返回套接字(否则每秒休眠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()
此函数没有理由返回
socket_to_server
。在由于
socket
对象是可变的,因此函数内部对它的任何更改(例如,将它连接到服务器)对调用它的函数都是可见的。在您可以通过在
^{pr2}$main()
中进行此更改来验证:见How do I pass a variable by reference?
相关问题 更多 >
编程相关推荐