搜尋
首頁後端開發Python教學python 程式設計之twisted詳解及簡單實例

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 &#39;start&#39;
  
  def stopFactory(self): 
    print &#39;stop&#39;
  
reactor.listenTCP(8123, ChatFactory()) 
reactor.run()

感謝閱讀,希望能幫助大家,謝謝大家對本站的支持!

更多python 程式設計之twisted詳解及簡單實例相關文章請關注PHP中文網!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

舉一個場景的示例,其中使用Python列表比使用數組更合適。舉一個場景的示例,其中使用Python列表比使用數組更合適。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python數組中訪問元素?您如何在Python數組中訪問元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Apr 28, 2025 pm 04:34 PM

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

Python中的模塊和包裝是什麼?Python中的模塊和包裝是什麼?Apr 28, 2025 pm 04:33 PM

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

Python中的Docstring是什麼?Python中的Docstring是什麼?Apr 28, 2025 pm 04:30 PM

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具