| If we abstract network commands, all network services are basically the same, except the service ports. The linereceiver class helps encapsulate these commands. Consider using linereceiver to implement a robot. 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]) Before starting this robot, we need to talk about the state machine. Many twisted protocols require a state machine to record the current state. The following are some suggestions: 1. Do not write too large, too complicated. The state machine should process only one level of abstraction at a time. 2. Create an open ended state machine, such as an SMTP client, dynamically using the Python language. 3. Do not mix protocol processing code with application-related code. Complete code: 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. # Start the service Factory = answerfactory () Reactor. listentcp (8007, factory) Reactor. Run () Client connection: 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. |