twisted簡單聊天室

來源:互聯網
上載者:User

要能 註冊使用者

     記錄線上使用者,資訊和串連(protocol)

     使用者離開

     向其他所有使用者發資訊


使用者狀態不能放到protocol中,因此factory中應該保留一個字典,記錄使用者名稱和protocol

protocol初始化時(新使用者串連),選項組是未註冊,提醒其輸入使用者名稱,然後還需要保留上面字典,檢測是否重名。如果未重名,將其狀態改變為登入。在字典中加入自己 name和protocol

註冊完之後,就可以向其他所有使用者廣播資訊(從字典中擷取protocol,發送資料)。

離開時,將資訊從字典中刪除


下面例子中使用了LineReveiver而不是Protocol,不過用法差不多


from twisted.internet.protocol import Factoryfrom twisted.internet import reactorfrom twisted.protocols.basic import LineReceiverclass ChatProtocol(LineReceiver):     def __init__(self, factory):          self.factory = factory          self.name = None          self.state = 'register'     def connectionMade(self):          self.sendLine('please input name :')     def handleRegister(self, name):          if name in self.factory.users:               self.sendLine('name taken, choose another name')               return          self.sendLine('Welcom %s!' % (name,))          self.name = name          self.factory.users[name] = self          self.state = 'chat'          self.broadCastMessage('%s has joined' % (name,))     def handleChat(self, line):          message = '<%s> %s' % (self.name, line)          self.broadCastMessage(message)     def lineReceived(self, line):          if self.state == 'register':               self.handleRegister(line)          else:               self.handleChat(line)     def connectionLost(self, reason):          if self.name in self.factory.users:               del self.factory.users[self.name]               self.broadCastMessage('%s has left '% (self.name,) )                    def broadCastMessage(self, message):          for name, protocol in self.factory.users.iteritems():               if protocol != self :                    protocol.sendLine(message)class ChatFactory(Factory):     def __init__(self):          self.users = {}     def buildProtocol(self, addr):          return ChatProtocol(self)reactor.listenTCP(8000, ChatFactory())reactor.run()

使用telnet localhost 8000來進行測試

使用twisted的一般步驟:

    1)定義Protocol類,前面的例子中繼承了twisted.internet.protocol.Protocol類或者twisted.protocols.basic.LineRecevier

    2)定義Factory類,伺服器端繼承twisted.internet.protocol.Factory,用戶端繼承twisted.internet.protocol.ClientFactory。Factory類建立protocol執行個體並儲存了可共用資訊。

    3)伺服器端綁定連接埠,用戶端串連到目標連接埠

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.