【问题标题】:python twisted simple client - server communicationpython扭曲的简单客户端-服务器通信
【发布时间】:2012-09-27 11:47:52
【问题描述】:

试图让一个简单的 python 扭曲客户端 - 服务器应用程序正常工作。目的是用它来控制一些 IRC 机器人;就像一个主控制台向所有(5ish)机器人发出命令。

附加的代码有一天会变成服务器代码。目前,我正在使用 telnet 来模拟 IRC 机器人(客户端)连接到“party line”。

我坚持的是,我如何从附加的服务器应用程序,sendLine 到所有机器人?每次我创建一个循环来获取 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 提示不断提示输入,而不仅仅是在收到一条线之类的事件之后 - 一直.. 我希望服务器机器人控制台始终准备好接受我的输入并将 sendLine 发送到所有机器人。

sendLine(raw_input("> "))

【问题讨论】:

    标签: python client twisted irc


    【解决方案1】:

    根本不要使用raw_input。相反,实例化一个stdio.StandardIO,给它的构造函数一个你的LineReceiver 子类的实例。只要stdin 上有新行可用,就会调用您在子类中定义的lineReceived,然后您可以将其广播给机器人。

    This example from the Twisted site 演示了这个想法。

    【讨论】:

    • 您能再解释一下吗?我对 Python 和 OOP 很陌生——也许是一个简单的例子?我不希望答案一目了然,如果不是太多工作,只是一个演示。谢谢! :)
    • 答案中链接了一个示例。你能描述一下你还想要什么例子吗?
    • 问题表明您的问题是 raw_input 阻止了 Twisted 应用程序的执行。请查看the link with the example provided in the answer。这是如何在 Twisted 中实现 raw_input 的非阻塞等效的直接且简单的演示。如果您的问题与其他问题有关,请随时对其进行编辑和澄清!
    • 我对如何将 LineReceiver 连接到 stdio.StandardIO 的实例有点迷茫。
    • @user1675884 你看过这个例子吗?使用 LineReceiver 实例作为构造函数的唯一参数来实例化 twisted.internet.stdio.StandardIO。它在示例的第 77 行。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    相关资源
    最近更新 更多