python基礎教程總結15——5 虛擬茶話會

來源:互聯網
上載者:User

標籤:

聊天伺服器:

  伺服器能接受來自不同使用者的多個串連;

  允許使用者同時(並行)操作;

  能解釋命令,例如,say或者logout;

  容易拓展

 

1. 初次實現

1.1 CharServer類

  有問題。。。。。。。。。。。。。。。。

#可接受已連線的服務器from asyncore import dispatcherimport asyncore,socketclass ChatServer(dispatcher):    def handle_accept(self):        conn.addr=self.accept()        print ‘Connection attempt  from‘, addr[0]   #用戶端的Ip地址s=ChatServer()s.create_socket(socket.AF_INET, socket.SOCK_STREAM)#建立通訊端s.bind((‘ ‘,5005))#將通訊端綁定到連接埠,Null 字元串(主機名稱),意味著本地主機(即本地所有介面),連接埠號碼為5005s.listen(5)  #告訴伺服器要監聽串連,並且指定5個串連的代辦的事物asyncore.loop() #啟動伺服器,迴圈監聽
#具有清理功能的基本伺服器from asyncore import dispatcherimport socket, asyncorePORT=5005class ChatServer(dispatcher):    def __init__(self,port):        dispatcher.__init__(self)        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)        self.set_reuse_addr()        self.bind((‘ ‘,port))        self.listen(5)    def  handle_accept(self):        conn, addr=self.accept()        print ‘Connection attempt from‘, addr[0]if __name__ =="__main__":    s=ChatServer(PORT)    try: asyncore.loop()    except KeyboardInterrupt: pass

 

1.2 CharSession類

1)set_terminator方法用於將行終止對象設為網路通訊協定中通常用作終止符的"\r\n"

2)ChatSession對象會將目前讀取的資料作為儲存為字串列表data。但讀入更多資料時,collect_incoming_data會自動被調用,將新讀入的資料追加到列表中。

3)found_terminiator方法在讀到終止對象時被調用

4)ChatServer儲存回話列表

5)CharServer的handle_accept方法現在建立了新的ChatSession對象,並將其追加到會話列表中

# 帶有ChatSession類的伺服器程式from asyncore import dispatcherfrom asynchat import async_chatimport  socket,asyncorePORT=5005class ChatSession(async_chat):    def __init__(self,sock):        async_chat.__init__(self,sock)        self.set_terminator("\r\n")        self.data=[]    def  collect_incoming_data(self,data):        self.data.append(data)        def  found_terminator(self):        line=‘ ‘.join(self.data)        self.data=[]        #處理該行資料        print lineclass ChatServer(dispatcher):    def __init__(self,port):        diapatcher.__init__(self)        self.create_socket(socket.AF_INET,socket.SOCK_STREAM)        self.set_reuse_addr()        self.bind((‘ ‘.port))        self.listen(5)        self.sessions=[]    def handle_accept(self):        conn,addr=self.accept()        self.sessions.append(ChatSession(com))if __name__ == ‘__main__‘:    s=ChatServer(PORT)    try: asyncore.loop()    except KeyboardInterrupt: print

 

1.3 整合

python基礎教程總結15——5 虛擬茶話會

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.