我正在尝试编写一个简单的服务器程序来打印发送给它的数据,或者在数据“退出”,“退出”或“停止”时退出:
HOST = ""
PORT = 37720
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(1)
while(1):
conn, addr = server.accept()
data = conn.recv(1024)
if not data: break
inData, inUrl = json.loads(data)
if inData == "quit" or inData == "exit" or inData == "stop":
print("Quitting")
conn.close()
break
else:
conn.send("Received")
print(inData)
它做了我所期望的,除了当我尝试再次运行服务器一旦它退出时,我得到:
Traceback (most recent call last):
File "./s", line 14, in <module>
server.bind((HOST, PORT))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
我认为这意味着连接未关闭。如何关闭它以防止这种情况?我尝试了conn.close()
,但没有解决任何问题。
答案 0 :(得分:3)
您需要设置SO_REUSEADDR标志。
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)