【问题标题】:Sockets and functions套接字和函数
【发布时间】: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 函数将是一个循环,直到客户端连接。

标签: python sockets


【解决方案1】:
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

这个函数没有理由返回socket_to_server。

由于socket 对象是可变的,因此在函数内部对其进行的任何更改(例如将其连接到服务器)对调用它的函数都是可见的。

您可以通过在main() 中进行此更改来验证这一点:

returned_sock = try_connecting_to_server(socket_to_server)
if returned_sock is socket_to_server:
    print "They refer to the exact same object!"

见How do I pass a variable by reference?

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多