如果我们把网络的命令抽象出来, 所有的网络服务基本上都一样, 除了服务端口不同而已.
LineReceiver类就是帮助封装这些命令的.
考虑用LineReceiver实现一个机器人.
- # -*- coding: utf-8 -*-
- from twisted.protocols.basic import LineReceiver
- class AnswerProtocol(LineReceiver):
- answers = {’How are you?’: ’Fine’, None : "I don’t know what you mean"}
- def lineReceived(self, line):
- if self.answers.has_key(line):
- self.sendLine(self.answers[line])
- else:
- self.sendLine(self.answers[None])
在我们启动这个机器人之前, 我们需要谈论一下状态机.
很多twisted协议处理中都需要状态机来记录当前的状态, 下面是一些建议:
1.不要编写过大, 过复杂的. 状态机应该一次只处理一个层次的抽象.
2. 使用python语言的动态性创建 open ended状态机, 比如SMTP客户端.
3. 不要把协议处理代码和应用相关代码混合.
完整的代码:
- # -*- coding: utf-8 -*-
- from twisted.protocols.basic import LineReceiver
- from twisted.internet.protocol import Protocol, Factory
- from twisted.internet import reactor
- class AnswerProtocol(LineReceiver):
- answers = {"How are you?": "Fine", None : "I don’t know what you mean"}
- def lineReceived(self, line):
- if self.answers.has_key(line):
- self.sendLine(self.answers[line])
- else:
- self.sendLine(self.answers[None])
- class AnswerFactory(Factory):
- protocol = AnswerProtocol
#开始启动服务
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.