1

我正在尝试编写一个程序,该程序将在某个端口(例如 tcp 6666)上侦听数据(简单的文本消息),然后将它们传递给一个或多个不同的协议 - irc、xmpp 等。我尝试了很多方法并挖掘了互联网,但我无法为此类任务找到简单且有效的解决方案。

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

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

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

访问 self 协议方法,因为:

self.protocol.dupa1(msg)

返回有关 self 未传递给活动协议对象的错误。或者,也许还有其他更好、更容易和更洁净的方法来创建具有多个协议的单个反应器,并在消息到达其中任何一个时触发动作,然后将该消息传递给其他协议进行处理/处理/发送?

任何帮助将不胜感激!

4

3 回答 3

5

这是从多个连接到端口 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 上。

于 2011-05-03T03:15:53.653 回答
3

常见问题解答中对此进行了回答。

http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother

于 2010-03-27T09:33:25.100 回答
1

doc/core/examples/chatserver.py。在那里,他们为Protocol'sconnectionMadeconnectionLost方法添加了钩子,以维护已连接客户端的列表,然后在消息到达以传递时遍历所有这些。

于 2010-03-26T18:31:11.353 回答