nim4n
nim4n

Reputation: 1829

how can I use callfromthread to call a method of a protocol in twisted?

I have a twisted web socket client protocol and I have another socket server in this reactor loop how can I access to sendMessage method from socket server? I see this link but I didn't get what should I do. I try this but I get some error:

reactor.callFromThread(WebSocketClientProtocol.sendMessage, protocol,  'data')
exceptions.TypeError: unbound method sendMessage() must be called with WebSocketClientProtocol instance as first argument (got module instance instead)

my websocket client:

class WebSocketProtocol(WebSocketClientProtocol):


   def sendHello(self):
      self.sendMessage("something")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print msg

websocket_factory = WebSocketClientFactory("ws://localhost:1025/ws")
websocket_factory.protocol = WebSocketProtocol
connectWS(websocket_factory)

I solve It by this code:

class WebSocketProtocol(WebSocketClientProtocol):


   def onOpen(self):
        self.factory.data = []
        self.factory.data.append(self)

reactor.callFromThread(WebSocketClientProtocol.sendMessage, websocket_factory.data[0],  send)

Upvotes: 2

Views: 1091

Answers (1)

Jean-Paul Calderone
Jean-Paul Calderone

Reputation: 48315

callFromThread is only for use when you have multiple threads in your program. Just because you have multiple servers doesn't mean you have multiple threads. In fact, Twisted is largely oriented towards running multiple servers (and/or clients) without using any extra threads.

The specific error you've encountered is about how you need to call an instance method on an instance, though.

WebSocketClientProtocol is a class and WebSocketClientProtocol.sendMessage is an unbound method. This is like trying to write:

class Foo(object):
    def bar(self):
        print "Foo.bar:", self

Foo.bar()

This doesn't work any better than what you tried because of course you need to have an instance:

foo = Foo()
...
foo.bar()

Upvotes: 4

Related Questions