python programming twisted details and simple examples

  • 2020-05-26 09:25:12
  • OfStack

twisted for python programming


I'm not good at writing socket code. 1 is that it is troublesome to write c, and 2 is that I don't have such requirements in daily life. Wait until you really want to know, only to find that you really need to improve in this area. Recently, I needed to write some Python code due to project reasons, so I realized how cool it was to develop socket under python.

For most socket, users only need to focus on three events. These are create, delete, and send and receive data, respectively. The twisted library in python can help us achieve just such a goal, and it is easy to use. The following code is from the twistedmatrix website, which I think is quite good. I will post it here to share with you. If you need to test, telnet localhost 8123 will do. If you need to process the signal in twisted, you can register the signal function, call reactor.stop () in the signal function, and then twisted will continue call stop_factory, so you can continue with the rest of the cleanup.

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 = None 
    self.state = "GETNAME" 
  def connectionMade(self): 
    self.sendLine("What's your name?") 
  def connectionLost(self, reason): 
    if in self.users: 
      del self.users[] 
  def lineReceived(self, line): 
    if self.state == "GETNAME": 
  def handle_GETNAME(self, name): 
    if name in self.users: 
      self.sendLine("Name taken, please choose another.") 
    self.sendLine("Welcome, %s!" % (name,)) = name 
    self.users[name] = self 
    self.state = "CHAT" 
  def handle_CHAT(self, message): 
    message = "<%s> %s" % (, message) 
    for name, protocol in self.users.iteritems(): 
      if protocol != self: 
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()) 

Thank you for reading, I hope to help you, thank you for your support of this site!

Related articles: