Spa*_*kMe 1 python irc xmpp twisted
我试图编写一个程序,在某些端口(比如tcp 6666)上监听数据(简单文本消息),然后将它们传递给一个或多个不同的协议 - irc,xmpp等等.我已经尝试了很多方法并挖掘了互联网,但我找不到容易和有效的解决方案来完成这样的任务.
我目前正在与之斗争的代码是:http://pastebin.com/ri7caXih
我想知道如何从对象:
ircf = ircFactory('asdfasdf','#asdf666')
获得访问自协议方法,因为这:
self.protocol.dupa1(MSG)
返回有关self未传递给活动协议对象的错误.或者也许还有其他的,更好的,更简单的,更犹豫的方式来创建具有多个协议的单个反应器,并且当消息到达其中任何一个时具有动作触发器,然后将该消息传递给其他协议以进行处理/处理/发送?
任何帮助将非常感谢!
下面是从端口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()
Run Code Online (Sandbox Code Playgroud)
测试:
nc -l 9000
python test.py
nc 9001
Run Code Online (Sandbox Code Playgroud)
从任意数量的nc 9001(或netcat 9001)输入的数据将出现在nc -l 9000上.