如何在python程序中关闭Ctrl-C上的套接字连接 [英] How to close socket connection on Ctrl-C in a python programme

查看:70
本文介绍了如何在python程序中关闭Ctrl-C上的套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

any_connection = False

while True:
    try:
        conn, addr = s.accept()
        data = conn.recv(1024)
        any_connection = True

        # keep looking
        if not data: continue

        pid = os.fork()

        if pid == 0:
            server_process(data, conn)
    except KeyboardInterrupt:
        break

if any_connection:
    print("Closing connection")
    conn.close()

我在我用 Python 编写的无限运行的 TCP 服务器上捕获了 KeyboardInterrupt 信号.但是,即使我知道它正在关闭连接,因为它打印 Closing Connection,当我尝试重新运行服务器时,我得到:

I'm catching the KeyboardInterruptsignal here on an infinite-running TCP server I wrote in Python. However, even though I know it is closing the connection because it prints Closing Connection, when I try to re-run the server I get:

OSError: [Errno 48] 地址已被使用

我不知道发生了什么,因为我确信我正在调用 conn.close().

I have no idea what's happening because I know for sure I'm calling conn.close().

并且运行 killall python3 并没有修复它,除非我等待很长时间或更改端口,否则我一直收到错误消息.我也尝试 grep 所有 python3 进程,但我什么也没得到.

And running killall python3doesn't fix it, I keep getting the error unless I wait for a long time or change port. Also I tried to grep all python3 processes but I get nothing.

我正在运行 OS X Yosemite.

I'm running OS X Yosemite.

推荐答案

根据 docs错误 OSError: [Errno 48] Address already in use 发生的原因是之前执行的脚本使套接字处于 TIME_WAIT 状态,不能立即重用.这可以通过使用 socket.SO_REUSEADDR 标志来解决.

As per the docs the error OSError: [Errno 48] Address already in use occurs because the previous execution of your script has left the socket in a TIME_WAIT state, and can’t be immediately reused. This can be resolved by using the socket.SO_REUSEADDR flag.

例如:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))

这篇关于如何在python程序中关闭Ctrl-C上的套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆