twisted:基于python的twisted框架编写一个客户端和服务端的对话聊天空间
生活随笔
收集整理的這篇文章主要介紹了
twisted:基于python的twisted框架编写一个客户端和服务端的对话聊天空间
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
twisted:基于python的twisted框架編寫一個(gè)客戶端和服務(wù)端的對(duì)話聊天空間
?
?
目錄
輸出結(jié)果
實(shí)現(xiàn)代碼
?
?
?
輸出結(jié)果
更新……
?
?
實(shí)現(xiàn)代碼
#基于python的twisted框架編寫一個(gè)簡(jiǎn)單的聊天室 # -*- coding:utf-8 -*- from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor user = {} class ChatReci(LineReceiver): #定義一個(gè)類,這里繼承的是LineReceiverdef __init__(self): #初始化2個(gè)變量self.name = ''self.state = "game"def connectionMade(self): #連接協(xié)議,當(dāng)客戶端連接即發(fā)出消息self.sendLine("input you name?")def lineReceived(self, data): #這個(gè)函數(shù)定義了取名 打印歡迎界面,以及發(fā)送信息給連上來的用戶if self.name == '': #判斷名字是否為空 如果為空就進(jìn)行下面的操作self.name = data #給self.name賦值self.sendLine("you welcome, %s!" % (self.name)) #打印歡迎信息user[self.name] = self #賦值給userprint ('%s loging' %data) #打印登錄信息else: #不為空就打印信息message = "<%s> %s" % (self.name, data) #定義聊天信息for ur,protocol in user.items(): #取他的用戶名if protocol != user: #判斷他是不是一個(gè)用戶 如果不是就傳送消息protocol.sendLine(message) #傳送消息factory = Factory() #定義工廠 factory.protocol = ChatReci #綁定我的類 reactor.listenTCP(8000, factory) #綁定端口和工廠 reactor.run() #啟動(dòng)?
總結(jié)
以上是生活随笔為你收集整理的twisted:基于python的twisted框架编写一个客户端和服务端的对话聊天空间的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Py之twisted:Python库之t
- 下一篇: Py之BaseHTTPServer:Py