2011-10-04 218 views

回答

3

這裏是只使用標準庫的基本示例:

import SocketServer 
import threading 

class Handler(SocketServer.StreamRequestHandler): 

    def handle(self): 
     print self.client_address,'connected' 
     self.server.add_client(self.request) 
     while 1: 
      data = self.request.recv(1024) 
      if not data: break 
      self.server.send(self.request,data) 
     self.server.remove_client(self.request) 

class Server(SocketServer.ThreadingTCPServer): 

    def __init__(self,*args,**kwargs): 
     SocketServer.ThreadingTCPServer.__init__(self,*args,**kwargs) 
     self.clients = [] 
     self.lock = threading.Lock() 

    def add_client(self,c): 
     with self.lock: 
      self.clients.append(c) 

    def remove_client(self,c): 
     with self.lock: 
      self.clients.remove(c) 

    def send(self,sender,data): 
     with self.lock: 
      for c in self.clients: 
       if c is not sender: 
        c.sendall(data) 

s = Server(('',8000),Handler) 
s.serve_forever() 
+0

你真的應該使用'與self.lock:',而不是調用獲取和釋放自己 - 更短並避免了明顯的陷阱。 – Voo

+0

@Voo也許我正在使用Python 2.4:^)。謝謝,改變了。 –

+1

我的吊,是軟件依賴性的另一受害者:( – Voo