SendMessage with client in Python outside "EchoClientProtocol" class

#1

Hi,

I try to send message with a python client outside “EchoClientProtocol” class.

I use this example :

from twisted.internet ``import reactor

from autobahn.websocket ``import WebSocketClientFactory, \

``WebSocketClientProtocol, \

``connectWS

class EchoClientProtocol(WebSocketClientProtocol):

``def sendHello(``self``):

``self``.sendMessage(``"Hello, world!"``)

``def onOpen(``self``):

print "connected"

if __name__ ``=``= '__main__'``:

``factory ``= WebSocketClientFactory(``"ws://localhost:9000"``, debug ``= False``)

``factory.protocol ``= EchoClientProtocol

``connectWS(factory)

# I want to send a message when I'm here

``reactor.run()

If I put “self.sendHello()” into “onOpen”, data are sent well to server.

How I can call “sendHello” in main ? Like this ? :

factory.protocol.sendHello(EchoClientProtocol())

If I do that, the client connects to server but no data are sent. I think, it’s because “sendHello” must be call after “onOpen”. How I can do that ?

Thanks,

Kevin.

0 Likes

#2

If I put "self.sendHello()" into "onOpen", data are sent well to server.
>
How I can call "sendHello" in __main__ ? Like this ? :
factory.protocol.sendHello(EchoClientProtocol())

If I do that, the client connects to server but no data are sent. I
think, it's because "sendHello" must be call after "onOpen". How I can
do that ?

sendMessage() only works after the WebSocket connection has been established, which is the case when the onOpen() hook fires.

You cannot simply do that in "main" .. Twisted works asynchronously ..

/Tobias

0 Likes

#3

Thank you

0 Likes