twisted-02 ChatRoom

使用twisted编写的chatroom,使用windows自带的telenet作为客户端。

from twisted.internet.protocol import Factory
from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
from twisted.internet.endpoints import serverFromString


'''
window: use telnet localhost 8888
to enter chat room and chat with others
ctrl + ] to disconnect to server
'''

class ChatRoomProtocol(LineReceiver):
	def __init__(self):
		self._name = None

	def connectionMade(self):
		self.sendLine('What\'s your name?')

	def lineReceived(self, line):
		if not self._name:
			if not line.strip() or line in list(iter(self.factory._users)):
				self.sendLine('Your name is corrupt or invalid, please reinput your new name!')
				return

			self._name = line
			self.factory._users[line] = self 
			self.sendLine('Welcome %s to our chat room' % self._name)
			return

		msg = '%s says: %s' % (self._name, line)
		self.factory.boardMessage(msg)

	def connectionLost(self, reason):
		msg = '%s says: bye bye !' % self._name
		self.factory.boardMessage(msg)
		del self.factory._users[self._name]

class ChatRoomFactory(Factory):
	protocol = ChatRoomProtocol

	def __init__(self):
		self._users = {}

	def boardMessage(self, msg):
		for i in self._users:
			self._users[i].sendLine(msg)

if __name__ == '__main__':
	serverFromString(reactor, 'tcp:8888').\
			listen(ChatRoomFactory())
	reactor.run()





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值