Python xmpp jabber client in tornado web applicati

2019-07-10 17:08发布

问题:

I am desktop programmer but I want to learn something about web services. I decided for python. I am trying understand how web applications works. I know how to create basic tornado website (request - response) and working jabber client, but I don't know how to mix them. Can I use any python components in web services? Does they must have specific structure ( sync or async )? Because I'm stuck in loop handlers:

If tornado start web serwer by command:

app = Application()
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()

... so how (where) can I start xmpp loop?

client.connect()
client.run()

I think that tornado listen loop should handle xmpp listening, but don't know how

Regards.

Edit: I forgot. I am using pyxmpp2

回答1:

I believe what you are trying to accomplish is not feasible in one thread of python as both are trying to listen at the same time which isn't possible in one thread. Might I suggest looking at this tutorial on threading.

Another question would be are you trying to make a web based xmpp or just have a xmpp & html server running in the same script. If you wish to try the former I would advise you to look into inter-thread communication either with zeromq or queue



回答2:

maybe WebSocketHandler and Thread will help you.

Demo

class BotThread(threading.Thread):

    def __init__(self,my_jid,settings,on_message):
        super(BotThread,self).__init__()
        #EchoBot is pyxmpp2's Client
        self.bot = EchoBot(my_jid, settings,on_message= on_message)

    def run(self):
        self.bot.run()


class ChatSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self): 
        #init xmpp client
        my_jid = 
        settings = 
        bot =BotThread(my_jid, settings,on_message=self.on_message)
        bot.start()