Practice content: Socket,io multiplexing, Python Selectors library for simple group chat.
1. Service-side Code
1 __author__='Orcsir'2 ImportSelectors3 ImportThreading4 ImportSocket5 fromCollectionsImportNamedtuple6 7 8 classChatserver:9 def __init__(Self, ip="0.0.0.0", port=9527):TenSELF.ADDR =(IP, port) OneSelf.sock =Socket.socket () ASelf.selector =selectors. Defaultselector () -Self.data = Namedtuple ("Data", ["Callback","Datagram"]) - the defStart (self): - Self.sock.bind (SELF.ADDR) - Self.sock.listen () - self.sock.setblocking (False) +Self.selector.register (Self.sock, selectors. Event_read, Self.data (self.accept, b"")) -Threading. Thread (Target=self.select, name="Select"). Start () + A defSelect (self): at whileTrue: - Try: -Events =Self.selector.select () - except: - self.stop () - return in - forKey, MaskinchEvents: todata =Key.data +callback =Data.callback -Datagram =Data.datagram the Callback (Key.fileobj, mask, datagram) * $ defAccept (self, sock:socket.socket, mask, data):Panax Notoginsengconn, raddr =sock.accept () - conn.setblocking (False) theSelf.selector.register (conn, selectors. Event_read |selectors. Event_write, Self.data (self.recv_send, data)) + A #Processing Data Reception the def_process_recv (self, Conn:socket.socket, mask): + Try: -data = CONN.RECV (1024) $ except: $ Self.selector.unregister (conn) - conn.close () - return the - ifData:Wuyi forKeyinchSelf.selector.get_map (). VALUES (): the ifKey.fileobj! =Self.sock: -Datagram ="From {}. Contents: {}". Format (Conn.getpeername (), Data.decode ()). Encode () Wu self.selector.modify (key.fileobj, selectors. Event_write, Self.data (self.recv_send, datagram)) - Else: About Self.selector.unregister (conn) $ conn.close () - - #Handling Data Sending - def_process_send (self, conn:socket.socket, mask, datagram:bytes): A conn.send (datagram) +SELF.SELECTOR.MODIFY (conn, selectors. Event_read, Self.data (Self.recv_send, b"")) the - #Distribution Functions $ defrecv_send (self, conn:socket.socket, mask, datagram:bytes): the ifMask &selectors. Event_read: the SELF._PROCESS_RECV (conn, mask) the elifMask &selectors. Event_write: the Self._process_send (conn, mask, datagram) - in defStop (self): theConnects = [] the ifSelf.selector.get_map (): About forKeyinchSelf.selector.get_map (). VALUES (): the connects.append (key.fileobj) the the forConninchconnects: + Self.selector.unregister (conn) - conn.close () the self.selector.close ()Bayi the the if __name__=='__main__': -CS =Chatserver () - Cs.start () the whileTrue: thecmd = input (">>>") the ifCmd.strip () = ="quit": the cs.stop () - Break
2. Client code
1 __author__='Orcsir'2 3 ImportSocket4 ImportThreading5 ImportLogging6 7FORMAT ="% (message) s"8Logging.basicconfig (Format=format, level=logging.info)9 Ten One classchatclient: A def __init__(Self, ip="127.0.0.1", port=9527): -Self.sock =Socket.socket () -SELF.RADDR =(IP, port) the - defStart (self): - Self.sock.connect (SELF.RADDR) -Threading. Thread (TARGET=SELF._RECV, name="recv"). Start () + - def_recv (self): + whileTrue: A Try: atdata = SELF.SOCK.RECV (1024) - except: - self.sock.close () - return - ifData: -Logging.info ("recv: {}". Format (Data.decode ())) in Else: - self.sock.close () to return + - defSend (self, data:str): the Self.sock.send (Data.encode ()) * $ defStop (self):Panax Notoginseng ifSelf.sock: - self.sock.close () the + A defMain (): theCC =chatclient () + Cc.start () - whileTrue: $cmd = input (">>>") $ ifCmd.strip () = ="quit": - cc.stop () - return the cc.send (cmd) - WuyiMain ()
3. Start two Ipython analog clients
Basic knowledge of Python programming practice _007