套接字连接不会关闭?

时间:2013-12-12 01:48:23

标签: python sockets

我正在尝试编写一个简单的服务器程序来打印发送给它的数据,或者在数据“退出”,“退出”或“停止”时退出:

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(),但没有解决任何问题。

1 个答案:

答案 0 :(得分:3)

您需要设置SO_REUSEADDR标志。

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