Home >Backend Development >Python Tutorial >Detailed explanation and simple examples of twisted programming in python
Detailed explanation of twisted programming in python
Foreword:
I am not good at writing socket code. One is that it is more troublesome to write in C, and the other is that I usually have no need for this. Only when I really wanted to understand it did I realize that I really had areas to improve in this area. Recently, I needed to write some Python code for project reasons, and I discovered how cool it is to develop sockets under python.
For most sockets, users only need to pay attention to three events. These are creating, deleting, and sending and receiving data respectively. The twisted library in python can help us achieve such a goal, and it is not troublesome to use. The following code comes from the twistedmatrix website. I think it’s pretty good, so I’ll post it here to share it with you. If you need to test, just telnet localhost 8123. If you need to process signals in twisted, you can first register the signal function, call reactor.stop() in the signal function, and then twisted will continue to call stop_factory, so that you can continue to complete the remaining cleanup work.
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()
Thank you for reading, I hope it can help everyone, thank you for your support of this site!
For more detailed explanations and simple examples of twisted programming in python, please pay attention to the PHP Chinese website!