Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有办法检查套接字是否仍在运行?_Python_Sockets_Networking - Fatal编程技术网

Python 有没有办法检查套接字是否仍在运行?

Python 有没有办法检查套接字是否仍在运行?,python,sockets,networking,Python,Sockets,Networking,我需要在两个客户之间聊天。但我不知道插座何时关闭,有没有办法检查它是否关闭 下面是我需要修复的代码部分: def main(): """Implements the conversation with server.""" # Open client socket, Transport layer: protocol TCP, Network layer: protocol IP client_socket = socket.socket() client_soc

我需要在两个客户之间聊天。但我不知道插座何时关闭,有没有办法检查它是否关闭

下面是我需要修复的代码部分:

def main():
    """Implements the conversation with server."""
    # Open client socket, Transport layer: protocol TCP, Network layer: protocol IP
    client_socket = socket.socket()
    client_socket.connect((HOST_IP, PORT))

    # start conversation with new client in parallel thread
    name = input("enter your name ")
    protocol.send_request(client_socket, name)
    thread_for_responses = threading.Thread(target=get_responses,
                                            args=(client_socket, ))
    thread_for_responses.start()

    while True:
        # Get request from keyboard
        client_request_str = input()
        if client_request_str:  # if client_request_str not empty string
            # send request according to the protocol
            protocol.send_request(client_socket, client_request_str)
            # Get response from server

我需要检查套接字是否已关闭,而不是
为True
,这样它就不会因为使用关闭的套接字而陷入崩溃的循环。

Python程序员通常说请求原谅比请求许可更容易。他们的意思是“处理异常”

例如,不能被零除。以下是处理这一事实的两种方法:

def print_quotient(a, b):
    if b == 0:
        print("quotient is not a number")
    else:
        print("quotient is {}".format(a / b))
vs

这些函数的行为方式相同,因此采用哪种方法没有多大区别。这是因为
b
无法更改。这与您的示例不同,您的示例中的套接字可以更改。外部因素会影响它的状态,这会改变尝试使用它的行为(例如,发送字节)。在这种情况下,异常处理更为优越,因为它不必尝试确保不会出现任何问题,它只需在出现问题时进行处理。在任何情况下,代码都不会认为它已将所有内容设置为正确工作,然后发现它遗漏了某些内容


因此,当您使用套接字操作时,请对这些操作可能产生的任何异常应用异常处理。

假设有这样一种方法,并且您使用了它。当循环迭代开始使用套接字时,您能保证套接字仍然没有关闭吗?如果套接字在
isAlive()
send\u request
之间关闭会怎么样?这是一个非常小的时间窗口,我的聊天只是为了一个学校项目。如果你有什么建议,我很乐意看一看,我想说得最准确。一个插座正在“运行”,直到你关闭它。然而,它作为端点的连接可能会被丢弃,这是由读取或写入时的错误或读取时的流结束发出的信号。TCP或UDP中没有其他测试。
def print_quotient(a, b):
    try:
        print("quotient is {}".format(a / b))
    except ZeroDivisionError:
        print("quotient is not a number")