关闭后,直接在代码中再次使用ThreadingMixIn启动TCPServer。 (给'地址已经在使用')

时间:2011-03-07 09:52:20

标签: python sockets shutdown tcpserver

我尝试在Python中使用线程(ThreadingMixIn)编写TCPServer。问题是,当我尝试再次运行socket.error: [Errno 48] Address already in use时,我无法正常关闭它。这是触发问题的python代码的最小示例:

import socket
import threading
import SocketServer

class FakeNetio230aHandler(SocketServer.BaseRequestHandler):

    def send(self,message):
        self.request.send(message+N_LINE_ENDING)

    def handle(self):
        self.request.send("Hello\n")

class FakeNetio230a(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass):
        self.allow_reuse_address = True
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

if __name__ == '__main__':
    for i in range(2):
        fake_server = FakeNetio230a(("", 1234), FakeNetio230aHandler)
        server_thread = threading.Thread(target=fake_server.serve_forever)
        server_thread.setDaemon(True)
        server_thread.start()
        # might add some client connection here
        fake_server.shutdown()

所有主要代码应该是启动服务器,关闭它并再次运行它。但它会触发上述错误,因为第一次关闭后套接字尚未释放。

我认为设置self.allow_reuse_address = True可以解决问题,但这不起作用。当python程序完成后,我可以立即再次运行它,它可以启动服务器一次(但不是两次) 但是,当我随机化端口(例如,将1234替换为1234+i)时问题就消失了,因为没有其他服务器正在侦听该地址。

有一个类似的SO Q Shutting down gracefully from ThreadingTCPServer,但解决方案(将allow_reuse_address设置为True对我的代码不起作用,我不使用ThreadingTCPServer。)

我如何修改代码才能在代码中启动服务器两次?

更多信息:我这样做的原因是我想为我的python项目运行一些单元测试。这需要提供我的软件应连接的(假)服务器。

修改
我刚刚找到了问题的最正确答案:我必须在主执行代码的末尾添加fake_server.server_close()(在fake_server.shutdown()之后)。我在TCPServer实现的源文件中找到了它。它只是self.socket.close()

3 个答案:

答案 0 :(得分:4)

不知何故,fake_server在分配给它时没有取消绑定(在for语句的第一行)。

要解决此问题,只需在循环结束时删除fake_server

        del fake_server # force server to unbind

答案 1 :(得分:4)

这篇文章帮助我克服了未封闭的套接字问题。 我有同样的问题,想在这里发布我的TCP服务器类(和客户端方法)的简单实现。

我做了一个TCPThreadedServer课程。为了使用它需要继承,并且必须覆盖方法process(msg)。每次服务器收到消息msg时,重写的方法都会调用,如果它返回一个非None对象,它将作为字符串返回给连接的客户端。

from SocketServer import TCPServer, StreamRequestHandler, ThreadingMixIn
import threading

class TCPThreadedServer(TCPServer, ThreadingMixIn):
    class RequstHandler(StreamRequestHandler):
       def handle(self):
           msg = self.rfile.readline().strip()
           reply = self.server.process(msg)
           if reply is not None:
               self.wfile.write(str(reply) + '\n')

    def __init__(self, host, port, name=None):
        self.allow_reuse_address = True
        TCPServer.__init__(self, (host, port), self.RequstHandler)
        if name is None: name = "%s:%s" % (host, port)
        self.name = name
        self.poll_interval = 0.5

    def process(self, msg):
        """
        should be overridden
        process a message
        msg    - string containing a received message
        return - if returns a not None object, it will be sent back 
                 to the client.
        """
        raise NotImplemented

    def serve_forever(self, poll_interval=0.5):
        self.poll_interval = poll_interval
        self.trd = threading.Thread(target=TCPServer.serve_forever,
                                    args = [self, self.poll_interval],
                                    name = "PyServer-" + self.name)
        self.trd.start()

    def shutdown(self):
        TCPServer.shutdown(self)
        TCPServer.server_close(self)
        self.trd.join()
        del self.trd

我发现它很容易使用:

class EchoServerExample(TCPThreadedServer):
    def __init__(self):
        TCPThreadedServer.__init__(self, "localhost", 1234, "Server")

    def process(self, data):
        print "EchoServer Got: " + data
        return str.upper(data)

for i in range(10):
    echo = EchoServerExample()
    echo.serve_forever()

    response = client("localhost", 1234, "hi-%i" % i)
    print "Client received: " + response

    echo.shutdown()

我使用的方法:     导入套接字

def client(ip, port, msg, recv_len=4096, 
           timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
    msg = str(msg)
    response = None
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((ip, port))
        if timeout != socket._GLOBAL_DEFAULT_TIMEOUT:
            sock.settimeout(timeout)
        sock.send(msg + "\n")
        if recv_len > 0:
            response = sock.recv(recv_len)
    finally:
        sock.close()
        return response

享受它!

答案 2 :(得分:2)

将您的FakeNetio230a定义更改为:

class FakeNetio230a(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass):
        self.allow_reuse_address = True
        SocketServer.TCPServer.__init__(self,
                                        server_address,
                                        RequestHandlerClass,
                                        False)  # do not implicitly bind

然后,在FakeNetio230a实例化下方的入口点添加这两行:

fake_server.server_bind()    # explicitly bind
fake_server.server_activate()   # activate the server

以下是一个例子:

if __name__ == '__main__':
    for i in range(2):
        fake_server = FakeNetio230a(("", 1234), FakeNetio230aHandler)
        fake_server.server_bind()    # explicitly bind
        fake_server.server_activate()   # activate the server
        server_thread = threading.Thread(target=fake_server.serve_forever)
        server_thread.setDaemon(True)
        server_thread.start()
        # might add some client connection here
        fake_server.shutdown()