看了很多,不是很早不更新了,就是不支持gevent
最终选用了sleekxmpp
#!/usr/bin/env python # -*- coding: utf-8 -*- # https://github.com/fritzy/SleekXMPP/tree/develop/examples import sys if "threading" in sys.modules: print ("threading module loaded before patching!", "xmppclient") del sys.modules["threading"] from gevent import monkey; monkey.patch_all() from gevent.queue import Queue from sleekxmpp.util.misc_ops import setdefaultencoding; setdefaultencoding("utf8") import sleekxmpp import logging import gevent class XMPPClient(sleekxmpp.ClientXMPP): def __init__(self, jid, password, address): super(XMPPClient, self).__init__(jid, password) self.register_plugin("xep_0030") # Service Discovery self.register_plugin("xep_0004") # Data Forms self.register_plugin("xep_0060") # PubSub self.register_plugin("xep_0199") # XMPP Ping self.inbox = Queue() self.address = address self.job_send = None # 添加事件触发-启动触发 self.add_event_handler("session_start", self.session_start, threaded=True) # 添加事件触发-收消息触发 self.add_event_handler("message", self.message) if self.connect(address): self.process(block=False) print "xmpp connected" self.init() else: print "unable to connect." def session_start(self, event): """ Arguments: event -- An empty dictionary. The session_start event does not provide any additional data. """ self.send_presence() self.get_roster() # self.send_message(mto=self.target_jid, # mbody="ooxx", # mtype="chat") def message(self, msg): print msg["type"], msg["body"], msg["from"], msg["lang"] # if msg["type"] in ("chat", "normal"): # msg.reply("Thanks for sending\n%(body)s" % msg).send() def put_data(self, data): """发送消息函数 @param data: (target_jid, mtype, msg) """ self.inbox.put(data) def send_data(self): while True: data = self.inbox.get() target_jid, mtype, msg = data self.send_message(mto=target_jid, mbody=msg, mtype=mtype) def init(self): self.job_send = job_send = gevent.spawn(self.send_data) def _exit(glet): job_send.unlink(_exit) self.disconnect(wait=False) job_send.link(_exit) if __name__ == "__main__": logging.basicConfig(level=logging.ERROR, format="%(levelname)-8s %(message)s") xmpp = XMPPClient("[email protected]", "123456", ("the-xmpp-server-ip", 5222)) xmpp.put_data(("[email protected]", "chat", "ooxx")) xmpp = XMPPClient("[email protected]", "123456", ("the-xmpp-server-ip", 5222)) xmpp.put_data(("[email protected]", "chat", "xxoo")) gevent.wait()
时间: 2024-11-09 19:11:20