twisted-02 ChatRoom

来源:互联网 发布:苗阜与姜昆的关系知乎 编辑:程序博客网 时间:2024/05/17 18:14

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

from twisted.internet.protocol import Factoryfrom twisted.internet import reactorfrom twisted.protocols.basic import LineReceiverfrom twisted.internet.endpoints import serverFromString'''window: use telnet localhost 8888to enter chat room and chat with othersctrl + ] to disconnect to server'''class ChatRoomProtocol(LineReceiver):def __init__(self):self._name = Nonedef 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!')returnself._name = lineself.factory._users[line] = self self.sendLine('Welcome %s to our chat room' % self._name)returnmsg = '%s says: %s' % (self._name, line)self.factory.boardMessage(msg)def connectionLost(self, reason):msg = '%s says: bye bye !' % self._nameself.factory.boardMessage(msg)del self.factory._users[self._name]class ChatRoomFactory(Factory):protocol = ChatRoomProtocoldef __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