autobahn running in separate thread

#1

Hi,

thanks for a great library. I’m having some trouble getting started - I have a web app that I’m trying to connect through a websocket to another server running Tornado.

I need to be able to call sendMessage from outside the protocol class, which I’ve tried like this:

class Connection(threading.Thread):

def __init__(self):

	super(Connection, self).__init__()

def run(self):

	self.factory = WebSocketClientFactory("ws://127.0.0.1:8888/stream")

	self.factory.protocol = ClientProtocol

	connectWS(self.factory)

	reactor.run(installSignalHandlers=0)

def send(self, data):

	reactor.callFromThread(self.factory.protocol.sendMessage, data)

class ClientProtocol(WebSocketClientProtocol):

def onOpen(self):

print 'opened'

def onMessage(self, message, binary):

  print message

connection = Connection()

connection.daemon = True

connection.start()

connection.send(‘test’)

but I receive the following error:

Unhandled Error

Traceback (most recent call last):

File “/usr/lib/python2.7/threading.py”, line 524, in __bootstrap

self.__bootstrap_inner()

File “/usr/lib/python2.7/threading.py”, line 551, in __bootstrap_inner

self.run()

File “/usr/lib/python2.7/threading.py”, line 504, in run

self.__target(*self.__args, **self.__kwargs)

— —

File “/home/imran/Code/web/venv/local/lib/python2.7/site-packages/twisted/python/threadpool.py”, line 172, in _worker

result = context.call(ctx, function, *args, **kwargs)

File “/home/imran/Code/web/venv/local/lib/python2.7/site-packages/twisted/python/context.py”, line 118, in callWithContext

return self.currentContext().callWithContext(ctx, func, *args, **kw)

File “/home/imran/Code/web/venv/local/lib/python2.7/site-packages/twisted/python/context.py”, line 81, in callWithContext

return func(*args,**kw)

exceptions.TypeError: unbound method sendMessage() must be called with ClientProtocol instance as first argument (got str instance instead)

Any suggestions?

thank you,

imran

0 Likes

#2

The callFromThread method on Twisted reactor takes a callable as first arg, which if you want to call a method, should be an _unbound_ method. You then provide the instance (object) on which to call that method as a 2nd arg, and then any method args:

reactor.callFromThread(WebSocketProtocol.sendMessage, protocol, data)

···

Am 16.06.2013 18:36, schrieb Imran Akbar:

reactor.callFromThread(self.factory.protocol.sendMessage, data)

0 Likes