This article mainly introduces the twisted explanation of python programming and the relevant information of simple examples. if you need it, you can refer to the twisted explanation of python programming.
Preface:
I am not good at writing socket code. First, it is difficult to write data in c, and second, you do not have such requirements at ordinary times. When you really want to know about it, you will find that you need to improve it. Recently, some Python code needs to be written due to project reasons, so it is quite nice to develop socket under python.
For most sockets, users only need to pay attention to three events. Create, delete, and send and receive data respectively. The twisted Library in python can help us achieve this goal, and it is not difficult to use it. The following code is from the twistedmatrix website. I think it is quite good. I will share it with you here. If you need to test it, telnet localhost 8123. To process signals in twisted, register the signal function and call the reactor in the signal function. stop (), and then twisted continues to call stop_factory, so that you can continue to complete the remaining cleaning 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 this article. I hope it will help you. thank you for your support for this site!
For more details about python programming and simple examples of twisted, please follow the PHP Chinese network!