电梯直达 1# 发表于 2009-9-24 15:34:58 | 只看该作者 | 倒序浏览 如果我们把网络的命令抽象出来, 所有的网络服务基本上都一样, 除了服务端口不同而已. LineReceiver类就是帮助封装这些命令的. 考虑用LineReceiver实现一个机器人. 1. 2. # -*- coding: utf-8 -*- 3. 4. from twisted.protocols.basic import LineReceiver 5. 6. class AnswerProtocol(LineReceiver): 7. answers = {’How are you?’: ’Fine’, None : "I don’t know what you mean"} 8. 9. def lineReceived(self, line): 10. if self.answers.has_key(line): 11. self.sendLine(self.answers[line]) 12. else: 13. self.sendLine(self.answers[None]) 在我们启动这个机器人之前, 我们需要谈论一下状态机. 很多twisted协议处理中都需要状态机来记录当前的状态, 下面是一些建议: 1.不要编写过大, 过复杂的. 状态机应该一次只处理一个层次的抽象. 2. 使用python语言的动态性创建 open ended状态机, 比如SMTP客户端. 3. 不要把协议处理代码和应用相关代码混合. 完整的代码: 1. # -*- coding: utf-8 -*- 2. 3. from twisted.protocols.basic import LineReceiver 4. from twisted.internet.protocol import Protocol, Factory 5. from twisted.internet import reactor 6. 7. 8. class AnswerProtocol(LineReceiver): 9. answers = {"How are you?": "Fine", None : "I don’t know what you mean"} 10. 11. def lineReceived(self, line): 12. if self.answers.has_key(line): 13. self.sendLine(self.answers[line]) 14. else: 15. self.sendLine(self.answers[None]) 16. 17. 18. 19. class AnswerFactory(Factory): 20. protocol = AnswerProtocol 21. #开始启动服务 factory = AnswerFactory() reactor.listenTCP(8007, factory) reactor.run() 客户端连接: FunCat:~ Daniel$ telnet 127.0.0.1 8007 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. How are you? Fine What's your name? I don’t know what you mean Connection closed by foreign host.