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]地址已在使用中
我很困惑..
任何建议都将受到赞赏..
答案 0 :(得分:1)
而不是:
SocketServer.TCPServer.allow_reuse_address = True
它设置了您已经自己子类化的基类的值,(并创建了一个实例),
使用:
self.allow_reuse_address = True
答案 1 :(得分:0)
看起来你最后没有关闭套接字。尝试添加server.shutdown()
(以及更改allow_reuse_address
)以在线程加入后将其关闭。