TIME_WAIT issue after closing the socket

以下為我的範例程式。在程式結束後,依然會存在著TIME_WAIT連線,導致下次無法正常create socket server。

import socket
import os
import sys
 
def acceptConn(s):
	while True:
		conn = None
		try:
			conn, addr = s.accept()
			data = conn.recv(1024)
			data = data.strip()
 
			print data
			if data == 'exit':
				break
		except:
			print sys.exc_info()[0]
		finally:	
			if conn is not None:
				conn.close();
			conn = None
 
s = None
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.bind(('0.0.0.0', 4444))
	s.listen(1)
	acceptConn(s)
finally:
	if s is not None:
		s.shutdown(1)
		s.close()

原先我以為是socket沒有正確的關閉,因此調整了例外處理方式或者呼叫socket的shutdown。最後參考python document,在create socketc後做以下設定:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

這讓kernel知道我們可以重複使用TIME_WAIT的socket。