python - Twisted - 如何创建多协议(protocol)进程并在协议(protocol)之间发送数据

标签 python xmpp twisted irc

我正在尝试编写一个程序来监听某个端口(比如 tcp 6666)上的数据(简单的文本消息),然后将它们传递给一个或多个不同的协议(protocol)——irc、xmpp 等等。我已经尝试了很多方法并浏览了 Internet,但我无法为此类任务找到简单有效的解决方案。

我目前正在使用的代码在这里:http://pastebin.com/ri7caXih

我想知道如何从对象中获取:

ircf = ircFactory('asdfasdf', '#asdf666')

访问自协议(protocol)方法,因为:

self.protocol.dupa1(消息)

返回有关自身未传递给事件协议(protocol)对象的错误。或者,也许还有其他更好、更简单、更合理的方法来创建具有多个协议(protocol)的单个 react 器,并在消息到达其中任何一个时触发操作,然后将该消息传递给其他协议(protocol)以进行处理/处理/发送?

任何帮助将不胜感激!

最佳答案

这是从多个连接读取到端口 9001 并写出到端口 9000 上的连接的示例代码。您将需要多个“PutLine”实现,一个用于 XMPP、IRC、MSN 等。

我使用了一个全局变量来存储输出连接 PutLine,但您可能想要创建一个更复杂的 Factory 对象来处理它。

#!/usr/bin/env python

from twisted.internet.protocol import Protocol, Factory
from twisted.internet.endpoints import clientFromString, serverFromString
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

queue = []
putter = None

class GetLine(LineReceiver):
    delimiter = '\n'

    def lineReceived(self, line):
        queue.append(line)
        putter.have_data()
        self.sendLine(line)

class PutLine(LineReceiver):
    def __init__(self):
        global putter
        putter = self
        print 'putline init called %s' % str(self)

    def have_data(self):
        line = queue.pop()
        self.sendLine(line)


def main():
    f = Factory()
    f.protocol = PutLine
    endpoint = clientFromString(reactor, "tcp:host=localhost:port=9000")
    endpoint.connect(f)
    f = Factory()
    f.protocol = GetLine
    endpoint2 = serverFromString(reactor, "tcp:port=9001")
    endpoint2.listen(f)
    reactor.run()

if __name__ == '__main__':
    main()

测试:

nc -l  9000
python test.py
nc 9001

从任意数量的 nc 9001(或 netcat 9001)输入的数据将出现在 nc -l 9000 上。

关于python - Twisted - 如何创建多协议(protocol)进程并在协议(protocol)之间发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2525644/

相关文章:

python - 我如何与假装成终端的子进程进行交互?

python - python扭曲静态文件中的变量替换

javascript - Flask JWT扩展设置cookie错误

ios - didReceiveMessage :(XMPPMessage *)message Not Running Actual Device

ios - 无法使用用户名和密码登录以在 Xmpp 中聊天

当我尝试定义数据库设置时出现 java.net.BindException 。这是为什么?

python - 扭曲的框架服务器作为客户端建立连接?

python - 从抓取元素中提取日期和其他数据

python - 在python中查找总和等于给定数字的不同子数组

python - 为什么 scipy poisson 没有 pdf(概率密度函数)方法?