python 編程之twisted詳解
前言:
?我不擅長寫socket代碼。一是用c寫起來比較麻煩,二是自己平時也沒有這方面的需求。等到自己真正想了解的時候,才發現自己在這方面確實有需要改進的地方。最近由于項目的原因需要寫一些Python代碼,才發現在python下面開發socket是一件多么爽的事情。
??? 對于大多數socket來說,用戶其實只要關注三個事件就可以了。這分別是創建、刪除、和收發數據。python中的twisted庫正好可以幫助我們完成這么一個目標,實用起來也不麻煩。下面的代碼來自twistedmatrix網站,我覺得挺不錯的,貼在這里和大家分享一下。如果需要測試的話,直接telnet localhost 8123就可以了。如果需要在twisted中處理信號,可以先注冊signal函數,在signal函數中調用reactor.stop(),后面twisted繼續call stop_factory,這樣就可以繼續完成剩下的清理工作了。
from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor class Chat(LineReceiver): def __init__(self, users): self.users = users self.name = None self.state = "GETNAME" def connectionMade(self): self.sendLine("What's your name?") def connectionLost(self, reason): if self.name in self.users: del self.users[self.name] def lineReceived(self, line): if self.state == "GETNAME": self.handle_GETNAME(line) else: self.handle_CHAT(line) def handle_GETNAME(self, name): if name in self.users: self.sendLine("Name taken, please choose another.") return self.sendLine("Welcome, %s!" % (name,)) self.name = name self.users[name] = self self.state = "CHAT" def handle_CHAT(self, message): message = "<%s> %s" % (self.name, message) for name, protocol in self.users.iteritems(): if protocol != self: protocol.sendLine(message) class ChatFactory(Factory): def __init__(self): self.users = {} # maps user names to Chat instances def buildProtocol(self, addr): return Chat(self.users) def startFactory(self): print 'start' def stopFactory(self): print 'stop' reactor.listenTCP(8123, ChatFactory()) reactor.run()
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
