python聊天室
1. 如何用python編寫一個聊天室
首先需要一個聊天伺服器,這里繼承asyncore的dispatcher類來實現,代碼如下
class 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)
self.users = {}
self.main_room = ChatRoom(self)
def handle_accept(self):
conn, addr = self.accept()
ChatSession(self, conn)
2. 如何用Python編寫一個聊天室
Python3 計算 3/2 默認結果值為 1.5,這對新手程序員更加直觀。
Unicode表示
Python2 里如果你想將它保存為 Unicode,需要標記為 U 的字元串。
Python3 中的字元串默認存儲為 Unicode。在Python3,我們有個Unicode(UTF-8)字元串和 2 位元組類:位元組和位元組數組。
3. python區域網聊天室怎麼編寫表情代碼,用什麼方式打開,需要什麼插件嗎
要VB我給你代碼,Python不會
4. 如何用Python編寫一個聊天室
一、課程介紹
1.簡介
本次項目課是實現簡單聊天室程序的伺服器端和客戶端。
2.知識點
伺服器端涉及到asyncore、asynchat和socket這幾個模塊,客戶端用到了telnetlib、wx、time和thread這幾個模塊。
3.所需環境
本次課中編寫客戶端需要用到wxPython,它是一個GUI工具包,請先使用下面的命令安裝:
$ sudo apt-get install python-wxtools
密碼為shiyanlou
4.項目效果截圖
登錄窗口
二、項目實戰(伺服器端)
1.伺服器類
首先需要一個聊天伺服器,這里繼承asyncore的dispatcher類來實現,代碼如下
class 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)
self.users = {}
self.main_room = ChatRoom(self)
def handle_accept(self):
conn, addr = self.accept()
ChatSession(self, conn)
2.會話類
有了伺服器類還需要能維護每個用戶的連接會話,這里繼承asynchat的async_chat類來實現,代碼如下:
class ChatSession(async_chat):
"""
負責和單用戶通信
"""
def __init__(self, server, sock):
async_chat.__init__(self, sock)
self.server = server
self.set_terminator('
')
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)
def found_terminator(self):
'當客戶端的一條數據結束時的處理'
line = ''.join(self.data)
self.data = []
try:
self.room.handle(self, line)
except EndSession:
self.handle_close()
def handle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
3.命令解釋器
現在就需要一個命令解釋器能夠解釋用戶的命令,例如登錄、查詢在線用戶和發消息等,代碼如下:
class CommandHandler:
"""
命令處理類
"""
def unknown(self, session, cmd):
'響應未知命令'
session.push('Unknown command: %s
' % cmd)
def handle(self, session, line):
'命令處理'
if not line.strip():
return
parts = line.split(' ', 1)
cmd = parts[0]
try:
line = parts[1].strip()
except IndexError:
line = ''
meth = getattr(self, 'do_' + cmd, None)
try:
meth(session, line)
except TypeError:
self.unknown(session, cmd)
4.房間
接下來就需要實現聊天室的房間了,這里我們定義了三種房間,分別是用戶剛登錄時的房間、聊天的房間和退出登錄的房間,這三種房間都有一個公共的父類,代碼如下:
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):
'向所有的用戶發送指定消息'
for session in self.sessions:
session.push(line)
def do_logout(self, session, line):
'退出房間'
raise EndSession
class LoginRoom(Room):
"""
剛登錄的用戶的房間
"""
def add(self, session):
'用戶連接成功的回應'
Room.add(self, session)
session.push('Connect Success')
def do_login(self, session, line):
'登錄命令處理'
name = line.strip()
if not name:
session.push('UserName Empty')
elif name in self.server.users:
session.push('UserName Exist')
else:
session.name = name
session.enter(self.server.main_room)
class ChatRoom(Room):
"""
聊天用的房間
"""
def add(self, session):
'廣播新用戶進入'
session.push('Login Success')
self.broadcast(session.name + ' has entered the room.
')
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.
')
def do_say(self, session, line):
'客戶端發送消息'
self.broadcast(session.name + ': ' + line + '
')
def do_look(self, session, line):
'查看在線用戶'
session.push('Online Users:
')
for other in self.sessions:
session.push(other.name + '
')
class LogoutRoom(Room):
"""
用戶退出時的房間
"""
def add(self, session):
'從伺服器中移除'
try:
del self.server.users[session.name]
except KeyError:
pass
5.伺服器端完整代碼
#!/usr/bin/python
# encoding: utf-8
from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore
PORT = 6666 #埠
class EndSession(Exception):
"""
自定義會話結束時的異常
"""
pass
class CommandHandler:
"""
命令處理類
"""
def unknown(self, session, cmd):
'響應未知命令'
session.push('Unknown command: %s
' % cmd)
def handle(self, session, line):
'命令處理'
if not line.strip():
return
parts = line.split(' ', 1)
cmd = parts[0]
try:
line = parts[1].strip()
except IndexError:
line = ''
meth = getattr(self, 'do_' + cmd, None)
try:
meth(session, line)
except TypeError:
self.unknown(session, cmd)
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):
'向所有的用戶發送指定消息'
for session in self.sessions:
session.push(line)
def do_logout(self, session, line):
'退出房間'
raise EndSession
class LoginRoom(Room):
"""
剛登錄的用戶的房間
"""
def add(self, session):
'用戶連接成功的回應'
Room.add(self, session)
session.push('Connect Success')
def do_login(self, session, line):
'登錄命令處理'
name = line.strip()
if not name:
session.push('UserName Empty')
elif name in self.server.users:
session.push('UserName Exist')
else:
session.name = name
session.enter(self.server.main_room)
class ChatRoom(Room):
"""
聊天用的房間
"""
def add(self, session):
'廣播新用戶進入'
session.push('Login Success')
self.broadcast(session.name + ' has entered the room.
')
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.
')
def do_say(self, session, line):
'客戶端發送消息'
self.broadcast(session.name + ': ' + line + '
')
def do_look(self, session, line):
'查看在線用戶'
session.push('Online Users:
')
for other in self.sessions:
session.push(other.name + '
')
class LogoutRoom(Room):
"""
用戶退出時的房間
"""
def add(self, session):
'從伺服器中移除'
try:
del self.server.users[session.name]
except KeyError:
pass
class ChatSession(async_chat):
"""
負責和單用戶通信
"""
def __init__(self, server, sock):
async_chat.__init__(self, sock)
self.server = server
self.set_terminator('
')
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)
def found_terminator(self):
'當客戶端的一條數據結束時的處理'
line = ''.join(self.data)
self.data = []
try:
self.room.handle(self, line)
except EndSession:
self.handle_close()
def handle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
class 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)
self.users = {}
self.main_room = ChatRoom(self)
def handle_accept(self):
conn, addr = self.accept()
ChatSession(self, conn)
if __name__ == '__main__':
s = ChatServer(PORT)
try:
asyncore.loop()
except KeyboardInterrupt:
print
三、項目實戰(客戶端)
完成了伺服器端後,就需要實現客戶端了,這里客戶端連接伺服器使用了telnetlib模塊。
1.登錄窗口
這里的圖形界麵包選擇了wxPython,前面有安裝說明,登錄窗口通過繼承wx.Frame類來實現,代碼如下:
class LoginFrame(wx.Frame):
"""
登錄窗口
5. 關於python編程,寫一個聊天室中間出現的問題
知道無大神,屌絲一大群
6. 怎麼用python做一個聊天室不帶注釋,謝謝!
問題太大了兄弟,你怎麼不說怎麼做個淘寶京東呢。想要做聊天室,就要了解聊天室需要的技術,建議你看下python socket編程相關,一步一步來。比如先做一個無界面一問一答的雙人聊天室,然後做實時問答版的,在做多人實時聊天室版,再加上界面不就ok了,之後人多了系統扛不住了,在考慮如何提高系統性能。飯是一口一口吃,路是一步一步走。
7. 如何用Python編寫一個聊天室
python聊天室(python2.7版本):
暫時先給出兩種版本的,tcp+udp
都是分別運行server.py和client.py,就可以進行通訊了。
別外還有websocket版本,這個是有web界面的和基本web服務的,如果需要的話,我會把基本的代碼貼一版上來。
TCP版本:
socket-tcp-server.py(服務端):
#-*-encoding:utf-8-*-
#socket.getaddrinfo(host,port,family=0,socktype=0,proto=0,flags=0)
#根據給定的參數host/port,相應的轉換成一個包含用於創建socket對象的五元組,
#參數host為域名,以字元串形式給出代表一個IPV4/IPV6地址或者None.
#參數port如果字元串形式就代表一個服務名,比如「http」"ftp""email"等,或者為數字,或者為None
#參數family為地主族,可以為AF_INET,AF_INET6,AF_UNIX.
#參數socktype可以為SOCK_STREAM(TCP)或者SOCK_DGRAM(UDP)
#參數proto通常為0可以直接忽略
#參數flags為AI_*的組合,比如AI_NUMERICHOST,它會影響函數的返回值
#附註:給參數host,port傳遞None時建立在C基礎,通過傳遞NULL。
#該函數返回一個五元組(family,socktype,proto,canonname,sockaddr),同時第五個參數sockaddr也是一個二元組(address,port)
#更多的方法及鏈接請訪問
#Echoserverprogram
fromsocketimport*
importsys
importthreading
fromtimeimportctime
fromtimeimportlocaltime
importtraceback
importtime
importsubprocess
reload(sys)
sys.setdefaultencoding("utf8")
HOST='127.0.0.1'
PORT=8555#設置偵聽埠
BUFSIZ=1024
classTcpServer():
def__init__(self):
self.ADDR=(HOST,PORT)
try:
self.sock=socket(AF_INET,SOCK_STREAM)
print'%disopen'%PORT
self.sock.bind(self.ADDR)
self.sock.listen(5)
#設置退出條件
self.STOP_CHAT=False
#所有監聽的客戶端
self.clients={}
self.thrs={}
self.stops=[]
exceptException,e:
print"%disdown"%PORT
returnFalse
defIsOpen(ip,port):
s=socket(AF_INET,SOCK_STREAM)
try:
s.connect((ip,int(port)))
#s.shutdown(2)
#利用shutdown()函數使socket雙向數據傳輸變為單向數據傳輸。shutdown()需要一個單獨的參數,
#該參數表示s了如何關閉socket。具體為:0表示禁止將來讀;1表示禁止將來寫;2表示禁止將來讀和寫。
print'%disopen'%port
returnTrue
except:
print'%disdown'%port
returnFalse
deflisten_client(self):
whilenotself.STOP_CHAT:
print(u'等待接入,偵聽埠:%d'%(PORT))
self.tcpClientSock,self.addr=self.sock.accept()
print(u'接受連接,客戶端地址:',self.addr)
address=self.addr
#將建立的clientsocket鏈接放到列表self.clients中
self.clients[address]=self.tcpClientSock
#分別將每個建立的鏈接放入進程中,接收且分發消息
self.thrs[address]=threading.Thread(target=self.readmsg,args=[address])
self.thrs[address].start()
time.sleep(0.5)defreadmsg(self,address):
#如果地址不存在,則返回False
ifaddressnotinself.clients:
returnFalse
#得到發送消息的clientsocket
client=self.clients[address]
whileTrue:
try:
#獲取到消息內容data
data=client.recv(BUFSIZ)
except:
print(e)
self.close_client(address)
break
ifnotdata:
break
#python3使用bytes,所以要進行編碼
#s='%s發送給我的信息是:[%s]%s'%(addr[0],ctime(),data.decode('utf8'))
#對日期進行一下格式化
ISOTIMEFORMAT='%Y-%m-%d%X'
stime=time.strftime(ISOTIMEFORMAT,localtime())
s=u'%s發送給我的信息是:%s'%(str(address),data.decode('utf8'))
#將獲得的消息分發給鏈接中的clientsocket
forkinself.clients:
self.clients[k].send(s.encode('utf8'))
self.clients[k].sendall('sendall:'+s.encode('utf8'))
printstr(k)
print([stime],':',data.decode('utf8'))
#如果輸入quit(忽略大小寫),則程序退出
STOP_CHAT=(data.decode('utf8').upper()=="QUIT")
ifSTOP_CHAT:
print"quit"
self.close_client(address)
print"alreadyquit"
break
defclose_client(self,address):
try:
client=self.clients.pop(address)
self.stops.append(address)
client.close()
forkinself.clients:
self.clients[k].send(str(address)+u"已經離開了")
except:
pass
print(str(address)+u'已經退出')
if__name__=='__main__':
tserver=TcpServer()
tserver.listen_client()
——————————華麗的分割線——————————
socket-tcp-client.py(客戶端):
#-*-encoding:utf-8-*-
fromsocketimport*
importsys
importthreading
importtime
reload(sys)
sys.setdefaultencoding("utf8")
#測試,連接本機
HOST='127.0.0.1'
#設置偵聽埠
PORT=8555
BUFSIZ=1024
classTcpClient:
ADDR=(HOST,PORT)
def__init__(self):
self.HOST=HOST
self.PORT=PORT
self.BUFSIZ=BUFSIZ
#創建socket連接
self.client=socket(AF_INET,SOCK_STREAM)
self.client.connect(self.ADDR)
#起一個線程,監聽接收的信息
self.trecv=threading.Thread(target=self.recvmsg)
self.trecv.start()
defsendmsg(self):
#循環發送聊天消息,如果socket連接存在則一直循環,發送quit時關閉鏈接
whileself.client.connect_ex(self.ADDR):
data=raw_input('>:')
ifnotdata:
break
self.client.send(data.encode('utf8'))
print(u'發送信息到%s:%s'%(self.HOST,data))
ifdata.upper()=="QUIT":
self.client.close()
printu"已關閉"
break
defrecvmsg(self):
#接收消息,如果鏈接一直存在,則持續監聽接收消息
try:
whileself.client.connect_ex(self.ADDR):
data=self.client.recv(self.BUFSIZ)
print(u'從%s收到信息:%s'%(self.HOST,data.decode('utf8')))
exceptException,e:
printstr(e)
if__name__=='__main__':
client=TcpClient()
client.sendmsg()
UDP版本:
socket-udp-server.py
#-*-coding:utf8-*-
importsys
importtime
importtraceback
importthreading
reload(sys)
sys.setdefaultencoding('utf-8')
importsocket
importtraceback
HOST="127.0.0.1"
PORT=9555
CHECK_PERIOD=20
CHECK_TIMEOUT=15
classUdpServer(object):
def__init__(self):
self.clients=[]
self.beats={}
self.ADDR=(HOST,PORT)
try:
self.sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.sock.bind(self.ADDR)#綁定同一個域名下的所有機器
self.beattrs=threading.Thread(target=self.checkheartbeat)
self.beattrs.start()
exceptException,e:
traceback.print_exc()
returnFalse
deflisten_client(self):
whileTrue:
time.sleep(0.5)
print"hohohohohoo"
try:
recvData,address=self.sock.recvfrom(2048)
ifnotrecvData:
self.close_client(address)
break
ifaddressinself.clients:
senddata=u"%s發送給我的信息是:%s"%(str(address),recvData.decode('utf8'))
ifrecvData.upper()=="QUIT":
self.close_client(address)
ifrecvData=="HEARTBEAT":
self.heartbeat(address)
continue
else:
self.clients.append(address)
senddata=u"%s發送給我的信息是:%s"%(str(address),u'進入了聊天室')
forcinself.clients:
try:
self.sock.sendto(senddata,c)
exceptException,e:
printstr(e)
self.close_client(c)
exceptException,e:
#traceback.print_exc()
printstr(e)
pass
defheartbeat(self,address):
self.beats[address]=time.time()
defcheckheartbeat(self):
whileTrue:
print"checkheartbeat"
printself.beats
try:
forcinself.clients:
printtime.time()
printself.beats[c]
ifself.beats[c]+CHECK_TIMEOUT<time.time():
printu"%s心跳超時,連接已經斷開"%str(c)
self.close_client(c)
else:
printu"checkp%s,沒有斷開"%str(c)
exceptException,e:
traceback.print_exc()
printstr(e)
pass
time.sleep(CHECK_PERIOD)
defclose_client(self,address):
try:
ifaddressinself.clients:
self.clients.remove(address)
ifself.beats.has_key(address):
delself.beats[address]
printself.clients
forcinself.clients:
self.sock.sendto(u'%s已經離開了'%str(address),c)
print(str(address)+u'已經退出')
exceptException,e:
printstr(e)
raise
if__name__=="__main__":
udpServer=UdpServer()
udpServer.listen_client()
——————————華麗的分割線——————————
socket-udp-client.py:
#-*-coding:utf8-*-
importsys
importthreading
importtime
reload(sys)
sys.setdefaultencoding('utf-8')
importsocket
HOST="127.0.0.1"
PORT=9555
#BEAT_PORT=43278
BEAT_PERIOD=5
classUdpClient(object):
def__init__(self):
self.clientsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.HOST=HOST
self.ADDR=(HOST,PORT)
self.clientsock.sendto(u'請求建立鏈接',self.ADDR)
self.recvtrs=threading.Thread(target=self.recvmsg)
self.recvtrs.start()
self.hearttrs=threading.Thread(target=self.heartbeat)
self.hearttrs.start()
defsendmsg(self):
whileTrue:
data=raw_input(">:")
ifnotdata:
break
self.clientsock.sendto(data.encode('utf-8'),self.ADDR)
ifdata.upper()=='QUIT':
self.clientsock.close()
break
defheartbeat(self):
whileTrue:
self.clientsock.sendto('HEARTBEAT',self.ADDR)
time.sleep(BEAT_PERIOD)
defrecvmsg(self):
whileTrue:
recvData,addr=self.clientsock.recvfrom(1024)
ifnotrecvData:
break
print(u'從%s收到信息:%s'%(self.HOST,recvData.decode('utf8')))if__name__=="__main__":
udpClient=UdpClient()
udpClient.sendmsg()
8. 如何用Python編寫一個聊天室
#!/usr/bin/python
#encoding:utf-8
fromasyncoreimportdispatcher
fromasynchatimportasync_chat
importsocket,asyncore
PORT=6666#埠
classEndSession(Exception):
"""
自定義會話結束時的異常
"""
pass
classCommandHandler:
"""
命令處理類
"""
defunknown(self,session,cmd):
'響應未知命令'
session.push('Unknowncommand:%sn'%cmd)
defhandle(self,session,line):
'命令處理'
ifnotline.strip():
return
parts=line.split('',1)
cmd=parts[0]
try:
line=parts[1].strip()
exceptIndexError:
line=''
meth=getattr(self,'do_'+cmd,None)
try:
meth(session,line)
exceptTypeError:
self.unknown(session,cmd)
classRoom(CommandHandler):
"""
包含多個用戶的環境,負責基本的命令處理和廣播
"""
def__init__(self,server):
self.server=server
self.sessions=[]
defadd(self,session):
'一個用戶進入房間'
self.sessions.append(session)
defremove(self,session):
'一個用戶離開房間'
self.sessions.remove(session)
defbroadcast(self,line):
'向所有的用戶發送指定消息'
forsessioninself.sessions:
session.push(line)
defdo_logout(self,session,line):
'退出房間'
raiseEndSession
classLoginRoom(Room):
"""
剛登錄的用戶的房間
"""
defadd(self,session):
'用戶連接成功的回應'
Room.add(self,session)
session.push('ConnectSuccess')
defdo_login(self,session,line):
'登錄命令處理'
name=line.strip()
ifnotname:
session.push('UserNameEmpty')
elifnameinself.server.users:
session.push('UserNameExist')
else:
session.name=name
session.enter(self.server.main_room)
classChatRoom(Room):
"""
聊天用的房間
"""
defadd(self,session):
'廣播新用戶進入'
session.push('LoginSuccess')
self.broadcast(session.name+'hasenteredtheroom.n')
self.server.users[session.name]=session
Room.add(self,session)
defremove(self,session):
'廣播用戶離開'
Room.remove(self,session)
self.broadcast(session.name+'haslefttheroom.n')
defdo_say(self,session,line):
'客戶端發送消息'
self.broadcast(session.name+':'+line+'n')
defdo_look(self,session,line):
'查看在線用戶'
session.push('OnlineUsers:n')
forotherinself.sessions:
session.push(other.name+'n')
classLogoutRoom(Room):
"""
用戶退出時的房間
"""
defadd(self,session):
'從伺服器中移除'
try:
delself.server.users[session.name]
exceptKeyError:
pass
classChatSession(async_chat):
"""
負責和單用戶通信
"""
def__init__(self,server,sock):
async_chat.__init__(self,sock)
self.server=server
self.set_terminator('n')
self.data=[]
self.name=None
self.enter(LoginRoom(server))
defenter(self,room):
'從當前房間移除自身,然後添加到指定房間'
try:
cur=self.room
exceptAttributeError:
pass
else:
cur.remove(self)
self.room=room
room.add(self)
defcollect_incoming_data(self,data):
'接受客戶端的數據'
self.data.append(data)
deffound_terminator(self):
'當客戶端的一條數據結束時的處理'
line=''.join(self.data)
self.data=[]
try:
self.room.handle(self,line)
exceptEndSession:
self.handle_close()
defhandle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
classChatServer(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)
self.users={}
self.main_room=ChatRoom(self)
defhandle_accept(self):
conn,addr=self.accept()
ChatSession(self,conn)
if__name__=='__main__':
s=ChatServer(PORT)
try:
asyncore.loop()
exceptKeyboardInterrupt: