英文捉雞點 這裏 python
源碼中能夠看到其實本質上就對 select 以及 socket 的進一步封裝git
Python的asyncore模塊提供了以異步的方式寫入套接字服務的客戶端和服務器的基礎結構。github
英捉雞 , 這裏網絡
該模塊創建在asyncore
基礎架構之上,簡化了異步客戶端和服務器,而且更容易處理元素被任意字符串終止或者長度可變的協議。session
本次項目開發所須要用到的模塊和接口架構
用於建立 server_socket 套接字app
總體操做相似於 socket 的使用異步
import asynchat import asyncore # 定義端口 PORT = 6666 # 定義結束異常類 class EndSession(Exception): pass class ChatServer(asyncore.dispatcher): """ 聊天服務器 """ def __init__(self, port): asyncore.dispatcher.__init__(self) # 建立socket self.create_socket() # 設置 socket 爲可重用 self.set_reuse_addr() # 監聽端口 self.bind(('', port)) self.listen(5) self.users = {} self.main_room = ChatRoom(self) def handle_accept(self): conn, addr = self.accept() ChatSession(self, conn)
用於維護聊天室
重寫了 collect_incoming_data 用於數據存放
以及 found_terminator 來進行結束標誌
以及 handle_close 來進行結束操做
class ChatSession(asynchat.async_chat): """ 負責和客戶端通訊 """ def __init__(self, server, sock): asynchat.async_chat.__init__(self, sock) self.server = server self.set_terminator(b'\n') self.data = [] self.name = None self.enter(LoginRoom(server)) def enter(self, room): # 從當前房間移除自身,而後添加到指定房間 try: cur = self.room except AttributeError: pass else: cur.remove(self) self.room = room room.add(self) def collect_incoming_data(self, data): # 接收客戶端的數據 self.data.append(data.decode("utf-8")) def found_terminator(self): # 當客戶端的一條數據結束時的處理 line = ''.join(self.data) self.data = [] try: self.room.handle(self, line.encode("utf-8")) # 退出聊天室的處理 except EndSession: self.handle_close() def handle_close(self): # 當 session 關閉時,將進入 LogoutRoom asynchat.async_chat.handle_close(self) self.enter(LogoutRoom(self.server))
用於自定義協議, 相似於開發 httpserver 的時候的 協議格式定製處理
咱們預設了4種命令分別由 其同名函數進行分發處理
class CommandHandler: """ 命令處理類 """ def unknown(self, session, cmd): # 響應未知命令 # 經過 asynchat.async_chat.push 方法發送消息 session.push(('Unknown command {} \n'.format(cmd)).encode("utf-8")) def handle(self, session, line): line = line.decode() # 命令處理 if not line.strip(): return parts = line.split(' ', 1) cmd = parts[0] try: line = parts[1].strip() except IndexError: line = '' # 經過協議代碼執行相應的方法 method = getattr(self, 'do_' + cmd, None) try: method(session, line) except TypeError: self.unknown(session, cmd)
Room 類繼承了 CommandHandler 能夠處理聊天室中的命令處理
主要用於維護一個存有全部用戶的 sessions 列表以及 廣播發送信息處理
class Room(CommandHandler): """ 包含多個用戶的環境,負責基本的命令處理和廣播 """ def __init__(self, server): self.server = server self.sessions = [] def add(self, session): # 一個用戶進入房間 self.sessions.append(session) def remove(self, session): # 一個用戶離開房間 self.sessions.remove(session) def broadcast(self, line): # 向全部的用戶發送指定消息 # 使用 asynchat.asyn_chat.push 方法發送數據 for session in self.sessions: session.push(line) def do_logout(self, session, line): # 退出房間 raise EndSession
用戶登陸後須要廣播一條信息 xxx 加入聊天室
class LoginRoom(Room): """ 處理登陸用戶 """ def add(self, session): # 用戶鏈接成功的迴應 Room.add(self, session) # 使用 asynchat.asyn_chat.push 方法發送數據 session.push(b'Connect Success') def do_login(self, session, line): # 用戶登陸邏輯 name = line.strip() # 獲取用戶名稱 if not name: session.push(b'UserName Empty') # 檢查是否有同名用戶 elif name in self.server.users: session.push(b'UserName Exist') # 用戶名檢查成功後,進入主聊天室 else: session.name = name session.enter(self.server.main_room)
class LogoutRoom(Room): """ 處理退出用戶 """ def add(self, session): # 從服務器中移除 try: del self.server.users[session.name] except KeyError: pass
class ChatRoom(Room): """ 聊天用的房間 """ def add(self, session): # 廣播新用戶進入 session.push(b'Login Success') self.broadcast((session.name + ' has entered the room.\n').encode("utf-8")) self.server.users[session.name] = session Room.add(self, session) def remove(self, session): # 廣播用戶離開 Room.remove(self, session) self.broadcast((session.name + ' has left the room.\n').encode("utf-8")) def do_say(self, session, line): # 客戶端發送消息 self.broadcast((session.name + ': ' + line + '\n').encode("utf-8")) def do_look(self, session, line): # 查看在線用戶 session.push(b'Online Users:\n') for other in self.sessions: session.push((other.name + '\n').encode("utf-8"))
if __name__ == '__main__': s = ChatServer(PORT) try: print("chat server run at '0.0.0.0:{0}'".format(PORT)) asyncore.loop() except KeyboardInterrupt: print("chat server exit")
import wx import telnetlib from time import sleep import _thread as thread class LoginFrame(wx.Frame): """ 登陸窗口 """ def __init__(self, parent, id, title, size): # 初始化,添加控件並綁定事件 wx.Frame.__init__(self, parent, id, title) self.SetSize(size) self.Center() self.serverAddressLabel = wx.StaticText(self, label="Server Address", pos=(10, 50), size=(120, 25)) self.userNameLabel = wx.StaticText(self, label="UserName", pos=(40, 100), size=(120, 25)) self.serverAddress = wx.TextCtrl(self, pos=(120, 47), size=(150, 25)) self.userName = wx.TextCtrl(self, pos=(120, 97), size=(150, 25)) self.loginButton = wx.Button(self, label='Login', pos=(80, 145), size=(130, 30)) # 綁定登陸方法 self.loginButton.Bind(wx.EVT_BUTTON, self.login) self.Show() def login(self, event): # 登陸處理 try: serverAddress = self.serverAddress.GetLineText(0).split(':') con.open(serverAddress[0], port=int(serverAddress[1]), timeout=10) response = con.read_some() if response != b'Connect Success': self.showDialog('Error', 'Connect Fail!', (200, 100)) return con.write(('login ' + str(self.userName.GetLineText(0)) + '\n').encode("utf-8")) response = con.read_some() if response == b'UserName Empty': self.showDialog('Error', 'UserName Empty!', (200, 100)) elif response == b'UserName Exist': self.showDialog('Error', 'UserName Exist!', (200, 100)) else: self.Close() ChatFrame(None, 2, title='ShiYanLou Chat Client', size=(500, 400)) except Exception: self.showDialog('Error', 'Connect Fail!', (95, 20)) def showDialog(self, title, content, size): # 顯示錯誤信息對話框 dialog = wx.Dialog(self, title=title, size=size) dialog.Center() wx.StaticText(dialog, label=content) dialog.ShowModal()
class ChatFrame(wx.Frame): """ 聊天窗口 """ def __init__(self, parent, id, title, size): # 初始化,添加控件並綁定事件 wx.Frame.__init__(self, parent, id, title) self.SetSize(size) self.Center() self.chatFrame = wx.TextCtrl(self, pos=(5, 5), size=(490, 310), style=wx.TE_MULTILINE | wx.TE_READONLY) self.message = wx.TextCtrl(self, pos=(5, 320), size=(300, 25)) self.sendButton = wx.Button(self, label="Send", pos=(310, 320), size=(58, 25)) self.usersButton = wx.Button(self, label="Users", pos=(373, 320), size=(58, 25)) self.closeButton = wx.Button(self, label="Close", pos=(436, 320), size=(58, 25)) # 發送按鈕綁定發送消息方法 self.sendButton.Bind(wx.EVT_BUTTON, self.send) # Users按鈕綁定獲取在線用戶數量方法 self.usersButton.Bind(wx.EVT_BUTTON, self.lookUsers) # 關閉按鈕綁定關閉方法 self.closeButton.Bind(wx.EVT_BUTTON, self.close) thread.start_new_thread(self.receive, ()) self.Show() def send(self, event): # 發送消息 message = str(self.message.GetLineText(0)).strip() if message != '': con.write(('say ' + message + '\n').encode("utf-8")) self.message.Clear() def lookUsers(self, event): # 查看當前在線用戶 con.write(b'look\n') def close(self, event): # 關閉窗口 con.write(b'logout\n') con.close() self.Close() def receive(self): # 接受服務器的消息 while True: sleep(0.6) result = con.read_very_eager() if result != '': self.chatFrame.AppendText(result)
if __name__ == '__main__': app = wx.App() con = telnetlib.Telnet() LoginFrame(None, -1, title="Login", size=(320, 250)) app.MainLoop()
初始狀態
用戶操做
To build a functioning async_chat subclass your input methods collect_incoming_data() and found_terminator() must handle the data that the channel receives asynchronously. The methods are described below