尝试让一个简单的Python扭曲客户端-服务器应用程序工作。目的是用它来控制一些 IRC 机器人;就像一个主控制台向所有(5 个左右)机器人发出命令。
有一天,附加的代码将形成服务器代码。目前,我使用 telnet 来模拟连接到“派对线路”的 IRC 机器人(客户端)。
我所困惑的是,如何从附加的服务器应用程序向所有机器人发送 Line?每次我创建一个循环来获取 raw_input 时,我最终都会停止执行。我考虑过针对连接状态函数进行测试,但似乎找不到(如果连接为真,则为 raw_input 逻辑)。
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class bottalk(LineReceiver):
botlist = []
def lineReceived(self, line):
botlistspot = len(self.botlist)
self.botlist.append(line)
print self.botlist[botlistspot] + " checked in."
class botfactory(Factory):
def buildProtocol(self, addr):
return bottalk()
reactor.listenTCP(8123, botfactory())
reactor.run()
我尝试将以下 raw_input 放置在 LineReceiver 类的外部。一切都结束了..我希望这个 raw_input 提示不断提示输入,而不仅仅是在收到线路之类的事件之后 - 一直..我希望服务器机器人控制台始终准备好接受我的输入并向所有机器人发送Line。
sendLine(raw_input("> "))
最佳答案
根本不要使用raw_input
。相反,实例化一个 stdio.StandardIO
,为其构造函数提供一个 LineReceiver
子类的实例。每当 stdin
上有新行可用时,您在子类中定义的 lineReceived
就会被调用,然后您可以将其广播给机器人。
关于python 扭曲的简单客户端-服务器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761189/