Skip to main content
 首页 » 编程设计

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

2025年05月04日14freeliver54

我正在尝试编写一个程序来监听某个端口(比如 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 上。