套接字关闭并重新绑定-如何避免长时间等待? [英] Socket shutdown and rebind - How to avoid long wait?

查看:134
本文介绍了套接字关闭并重新绑定-如何避免长时间等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python中的套接字工作,并且在开发阶段,我需要经常终止并重新启动程序.

I'm working with socket in python, and being in development stage I need to kill and restart my program frequently.

问题在于,一旦杀死了我的python脚本,我就必须等待很长时间才能重新绑定侦听套接字.这是重现该问题的摘录:

The issue is that once killed my python script, I've to wait long time to be able to rebind the listen socket. Here's a snippet to reproduce the problem:

#!/usr/bin/env python3                                                          

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 4321))
try:
    s.listen(5)
    while True:
        (a, b) = s.accept()
        print(a.recv(1000))
except KeyboardInterrupt:
    print("Closing")
    s.shutdown(socket.SHUT_RDWR)
    s.close()

按C-z键运行例外代码,并调用shutdownclose函数,但是直到套接字超时(GNU/Linux环境)后,我才能重新启动程序.

Hitting C-z runs the except code, calling shutdown and close functions, but I'm not able to restart my program until the socket timeout (GNU/Linux environment).

如何避免这种情况?

推荐答案

我不确定如何在Python中执行此操作,但是您想设置SO_REUSEADDR套接字选项.

I'm not sure how to do it in Python, but you want to set the SO_REUSEADDR socket option.

这篇关于套接字关闭并重新绑定-如何避免长时间等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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