3
import SocketServer
import sys
from Queue import *
import threading

class CustomTCPServer(SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass, commandQueue=Queue):
        self.queue = commandQueue
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=False)
        SocketServer.TCPServer.allow_reuse_address = True
        self.server_bind()
        self.server_activate()

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        commandQueue = self.server.queue
        self.data = self.request.recv(1024).strip()
        try:
            commandQueue.put(self.data)
        except Queue.Empty:
            print 'Sorry.. Cannot accept any more.. Queue is full..'

def main():
    HOST = ''
    PORT = 50099
    commandQueue = Queue()
    server = CustomTCPServer((HOST, PORT), SingleTCPHandler, commandQueue)
    threadObject = threading.Thread(target=server.serve_forever)
        threadObject.setDaemon(True)
        threadObject.start()
    threadObject.join()

if __name__ == '__main__':
  main()

但是每当我第二次运行代码时,我都会收到 socket.error: [Errno 98] Address already in use 的消息

我很困惑..

任何建议将不胜感激..

4

2 回答 2

2

代替:

SocketServer.TCPServer.allow_reuse_address = True

它设置了您已经将自己子类化的基类的值(并创建了一个实例),

利用:

self.allow_reuse_address = True
于 2013-10-26T07:27:12.533 回答
0

It doesn't look like you're ever closing the socket at the end. Try adding a server.shutdown() (as well as changing the allow_reuse_address) to shut it down at the end after the thread join.

于 2013-10-26T07:32:36.823 回答