聊天室
# -*- coding: utf-8 -*- #DeepChat 0.1 #author:myhaspl@myhaspl.com #license:LGPL from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor class Chat(LineReceiver): def __init__(self,users,myfactory): self.users=users; self.name=None self.state="NAME" self.factory=myfactory def strutf8(selfr,showstr): retstr=showstr.encode('utf-8') return retstr def connectionMade(self): self.factory.connectedcount=self.factory.connectedcount+1 self.sendLine(self.strutf8(U"【deepchat】********本聊天室共 %d 人聊天********"%self.factory.connectedcount)) self.sendLine(self.strutf8(U"请输入您的妮称:")) def connectionLost(self,reason): self.factory.connectedcount=self.factory.connectedcount-1 self.sendLine(self.strutf8(U"%s 再见"%self.name)) if self.name in self.users: del self.users[self.name] def getName(self,myline): if myline in self.users: self.sendLine(self.strutf8(U"%s 已经登录,请不要重复登录!"% myline)) return self.name=myline self.users[self.name]=self self.state="CHAT" self.sendLine(self.strutf8(U"欢迎您,%s"%self.name)) def getChat(self,myline): mychat=myline.split("#") lcount=len(mychat) if lcount>1: if mychat[0] in self.users: self.users[mychat[0]].sendLine(self.strutf8(U"<%s> to <%s> : %s"%(self.name,mychat[0],mychat[1].decode('utf-8')))) else: self.sendLine(self.strutf8(U"warning: %s 没有登录聊天室!"%mychat[0])) else: for name,protocol in self.users.iteritems(): if protocol!=self: protocol.sendLine(self.strutf8(U"<%s>: %s"%(self.name,myline.decode('utf-8')))) def lineReceived(self,line): myline=line.strip() if myline=="": if self.state=="NAME": self.sendLine(self.strutf8(U"本聊天室不允许游客进入")) self.transport.loseConnection() return if self.state=="NAME": self.getName(myline) else: self.getChat(myline) class chatFactory(Factory): connectedcount=0 protocol=Chat def __init__(self): self.users={} self.myfactory=self def buildProtocol(self,addr): return Chat(self.users,self.myfactory) reactor.listenTCP(8001,chatFactory()) reactor.run()
[c:\~]$ telnet 120.55.*.* 8001
Connecting to 120.55.*.*:8001...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
【deepchat】********本聊天室共 2 人聊天********
请输入您的妮称:
xx2
欢迎您,xx2
磊柘城苛
<x3>: 柘城村要在地愿为连理枝地 夺厅要权志龙
<x2> to <xx2> : asdfasfasdfs
[c:\~]$ telnet 120.55.*.* 8001
Connecting to 120.55.*.*:8001...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
【deepchat】********本聊天室共 1 人聊天********
请输入您的妮称:
x1
欢迎您,x1
您好,大家好
<xx2>: 磊柘城苛
<x3>: 柘城村要在地愿为连理枝地 夺厅要权志龙