Socket shutdown and rebind - How to avoid long wai

2020-03-05 03:22发布

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

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()

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).

How can I avoid this?

1条回答
在下西门庆
2楼-- · 2020-03-05 04:00

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

查看更多
登录 后发表回答