twisted-02 ChatRoom

严欣怡
2023-12-01

使用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()





 类似资料: