[python]我不太相信有人会愿意看这个问题
我不太相信有人会愿意看这个问题, 代码这么长这么长, 要我自己都不想看, 但还是帖一下:
#!/usr/bin/python"MyTools.py"import timeimport Queueimport threadingdef clock(): strtime = time.ctime() index = strtime.index(":") return strtime[index-2:index+6]class MyThread(threading.Thread): def __init__(self, func, args): threading.Thread.__init__(self) self.func = func self.args = args def run(self): apply(self.func, self.args)class MyLock(object): def __init__(self): self.queue = Queue.Queue(1) def lock(self): self.queue.put("", True) def unlock(self): self.queue.get(True)
#!/usr/bin/python"Server.py"import sysimport socketimport MyToolsclass Server(object): def __init__(self, host, port, liscnt): self.tcpSerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcpSerSock.bind((host, port)) self.tcpSerSock.listen(liscnt) self.tcpCliSock = [] self.namelist = [] self.locker = MyTools.MyLock() self.running = True MyTools.MyThread(self.__command, ()).start() self.__mainloop() self.tcpSerSock.close() def __command(self): try: while raw_input().lower() != "quit": pass except (EOFError, KeyboardInterrupt): pass finally: self.running = False def __mainloop(self): while self.running: tcpCliSock, addr = self.tcpSerSock.accept() self.locker.lock() self.tcpCliSock.append(tcpCliSock) self.locker.unlock() MyTools.MyThread(self.__recv, (tcpCliSock,)).start() def __recv(self, tcpCliSock): BUFSIZ = 1024 name = "" while self.running: data = tcpCliSock.recv(BUFSIZ) if not data: break if not name: name = data data = " ".join((name, "\n+\n")) self.__send(data, tcpCliSock, True) self.namelist.append(name) else: data = " ".join((name, MyTools.clock(), "\n", data)) self.__send(data, tcpCliSock, False) if name: data = " ".join((name, "\n-\n")) self.__send(data, tcpCliSock, False) self.namelist.remove(name) self.locker.lock() self.tcpCliSock.remove(tcpCliSock) self.locker.unlock() tcpCliSock.close() def __send(self, data, tcpCliSock, bFirst): self.locker.lock() if bFirst: tcpCliSock.send(data + str(self.namelist)) for eachSock in self.tcpCliSock: if eachSock is not tcpCliSock: eachSock.send(data) self.locker.unlock()def main(): host = "" port = 34567 liscnt = 5 argc = len(sys.argv) if argc >= 2: port = int(sys.argv[1]) if argc >= 3: liscnt = int(sys.argv[2]) Server(host, port, liscnt)if __name__ == "__main__": main()
[解决办法]
直接使用twisted
[解决办法]
貌似你现在的情况是客户端服务端都是被动等待对方关闭。你试试在客户端__close方法里主动关闭连接,或者送特征字段让服务器来做这动作...
[解决办法]
我大概看了一下。楼主的帖子虽然长了点,但是,为人很不错,所以还是看看:)
既然知道是资源释放的问题,我想还是先解决这个问题。不知道,在解决资源释放的问题有什么困难?当一个客户端断开连接时,服务端检测到连接已断开,就进行资源回收。
对于通知线程退出的问题,我建议使用信号量或者队列事件等的通知方式。
对你的具体问题了解不多,所以,上述只是我的一点想法和建议。希望对你有用。
[解决办法]
while self.running: #~ data = tcpCliSock.recv(BUFSIZ) try: data = tcpCliSock.recv(BUFSIZ) except: break