码迷,mamicode.com
首页 > 其他好文 > 详细

twisted-02 ChatRoom

时间:2015-08-05 18:26:13      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:twisted   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()





版权声明:本文为博主原创文章,未经博主允许不得转载。

twisted-02 ChatRoom

标签:twisted   chatroom   

原文地址:http://blog.csdn.net/davidsu33/article/details/47300197

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!