The previous msg w/ attached code is the wrong code, please use the code attached to this msg, thank you and sorry for this.

Gabriel


Gabriel Rossetti wrote:
Hello everyone,

I wrote a small example that listens for xmpp msgs in a thread. The main program calls a function that blocks (using Condition.wait) until a msg has been received and then returns the msg. When a msg arrives, it is put in a variable in the thread's object, it then calls the notify() attr on the Condition object. For some reason, this doesn't work, the thread gets the msg, tries to notify the Condition object, fails because the lock has not been acquired yet and blocks. I tried ignoring the failure, thinking that since it has not been acquired yet then when it is, it will get the msg right away and never call Condition.wait, thus not causing any problems, but this does not work either. Does someone know what I am doing wrong? I attached the code to this msg.

Thank you,
Gabriel
from __future__ import with_statement
import xmpp, sys
from threading import Thread, Condition, Event


class Listener(Thread):
    def __init__(self, ws):
        Thread.__init__(self)
        self.interrupt = Event()
        self.message = None
        self._cv = ws._cv
        self.client = ws._client
        self.client.RegisterHandler('message', self.onMessage)
    
    def onMessage(self, conn, msg):
        self.message = msg
        try:
            self._cv.notify()
        except RuntimeError:
            print "self._cv has not acquired the lock yet"
    
    def getMsg(self):
        return self.message
    
    def run(self):
        try:
            while(not self.interrupt.isSet()):
                self.client.Process(1)
        except KeyboardInterrupt:
            return 0

class WS(object):
    def __init__(self, username, password, res):
        self._jid = xmpp.protocol.JID(username)
        self._client = xmpp.Client(self._jid.getDomain())
        self._cv = Condition()
        
        if(self._client.connect(server=("localhost", 5222)) == ""):
            raise Exception("Error while connecting!")
        
        if(self._client.auth(self._jid.getNode(), password, res) is None):
            raise Exception("Authentication failed!")
        
        self._client.sendInitPresence()
        
        self._listener = Listener(self)
        self._listener.start()
    
    def getMsg(self, mid=None):
        """
        """
        with self._cv:
            res = self._listener.getMsg()
            while not res:
                self._cv.wait()
                res = self._listener.getMsg()
            return res

if(__name__ == "__main__"):
    ws = WS("t...@localhost", "123", "test")
    res = ws.getMsg()
    print "I just received : %s" % str(res)
    sys.exit(0)
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to