【问题标题】:Python - safely close socket connection on terminal from keyboard input besides cntrl-c?Python - 除了ctrl-c之外,从键盘输入安全地关闭终端上的套接字连接?
【发布时间】:2023-03-27 02:45:02
【问题描述】:

我正在与之通信的服务器有流会话槽,有时流会话无法打开,因为所有流会话槽都已使用。我怀疑它是因为我正在构建一个与服务器对话的程序,并且当我 cntrl-c 强制停止流时它不会安全关闭,从而保持流会话插槽为服务器上的该实例连接打开。所以当我终止程序几十次时,这个错误就会累积起来

我对 Python Networking 了解不多,不知道 cntrl-c 是否像敲击键并调用方法 close_conn(sock) 一样干净,但我想尝试一下。

假设我在我的终端上运行它"

 ...
    print("Now listening from server for data...\n")
      while True:

        received = sock.recv(1024) 

        #pseudo_code
        if (user_input == "e") close_conn(sock) 

出于调试目的,如何安全地关闭连接?

【问题讨论】:

    标签: python sockets python-sockets


    【解决方案1】:

    如果你想在按下“Ctrl + C”时关闭你的socket,然后等待另一个连接,你可以试试下面的代码。

    while True:
        try:
            received = sock.recv(1024)
        except KeyboardInterrupt:
            print "i want to close client socket"
            sock.close()
            break
        except socket.error, e:
            print "a socket erro has occured, e = ", e
            break
    

    【讨论】:

      【解决方案2】:

      重新阅读您的问题后,我想我回答了其他问题。对不起。

      我不知道您是否正确识别了问题的根源,但您可以将代码放在try...except...finally... 结构中。如果您不需要其中之一,可以省略 exceptfinally

      例如:

      from time import sleep
      try:
          sleep(10)
      except KeyboardInterrupt:
          print "This line is printed only if Ctrl+C was pressed"
      finally:
          print "This line is printed even if Ctrl+C was pressed"
      

      【讨论】:

        【解决方案3】:

        使用你所说的代码

        “你想试试...given code...

        。你快到了,只需要一条额外的线。见下文。

        ...
        print("Now listening from server for data...\n")
        while True:
        
            received = sock.recv(1024)  
        
            # code
            if user_input == "e":
                break #breaks out of while loop and calls close_conn(sock)
        close_conn(sock) 
        

        根据您的代码,我假设close_conn(sock) 是一个调用sock.close() 的函数,user_input 是一个变量,当它等于"e" 时,它会中断循环以关闭套接字。

        【讨论】:

          猜你喜欢
          • 2015-02-06
          • 2016-08-26
          • 2016-04-14
          • 2022-11-16
          • 2011-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-20
          相关资源
          最近更新 更多