Python network programming (about twisted)
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.
from twisted.internet.protocol import Factoryfrom twisted.protocols.basic import LineReceiverfrom twisted.internet import reactorclass 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)reactor.listenTCP(8123, ChatFactory())reactor.run()