从ThreadingTCPServer正常关闭

时间:2010-06-29 03:24:25

标签: python tcp socketserver

我已经基于示例here创建了一个运行ThreadingTCPServer的简单测试应用程序(Python 2.6.1)。如果客户端发送命令“bye”,我想关闭服务器并从应用程序中彻底退出。退出部分工作正常,但当我尝试重新运行应用程序时,我得到:

socket.error: [Errno 48] Address already in use

我尝试了here给出的解决方案来设置套接字选项,但这似乎没有帮助。我已经尝试了各种方法关闭服务器,但总是得到相同的错误。

知道我做错了吗?

import SocketServer
import socket
import sys
import threading
import time

class RequestHandler(SocketServer.BaseRequestHandler):

    def setup(self):
        print("Connection received from %s" % str(self.client_address))
        self.request.send("Welcome!\n")

    def handle(self):
        while 1:
            data = self.request.recv(1024)
            if (data.strip() == 'bye'):
                 print("Leaving server.")
                 self.finish()
                 self.server.shutdown()
                 # None of these things seem to work either
                 #time.sleep(2)
                 #del self.server.socket
                 #self.server.socket.shutdown(socket.SHUT_WR)
                 #self.server.socket.close()
                 #self.server.server_close()
                 break


    def finish(self):
        self.request.send("Goodbye!  Please come back soon.")

if __name__ == "__main__":
       server = SocketServer.ThreadingTCPServer(("localhost", 9999), RequestHandler)
       # This doesn't seem to help.
       #server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
       #server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
       server.serve_forever()
       print("Exiting program.")

1 个答案:

答案 0 :(得分:1)

如果您还没有找到答案,我相信这可能会有所帮助......

How to close a socket left open by a killed program?

然而,这与Alex提供的解决方案相同,所以也许这只是一个结束旧问题的机会。