autobahn in synchronous mode

I am trying to figure out if I can write a websocket client that does a simple connect/read/disconnect in a synchronous manner. The problem is that autobahn seems to want to keep connections open and listen for new message for an extended period of time. Is what I’m looking for possible with autobahn using either twisted or asyncio?


autobahn is designed to be async though understanding what you want, do you think something like this work for you. The below client connects to a server, sends a message, waits for the reply and closes the connection. You could just adjust this to your needs ?

import asyncio

from autobahn.asyncio.websocket import WebSocketClientProtocol, \

class MyClientProtocol(WebSocketClientProtocol):

    def onConnect(self, response):
        print("Server connected: {0}".format(response.peer))

    def onOpen(self):
        print("WebSocket connection open.")
        self.sendMessage(u"Hello, world!".encode('utf8'))

    def onMessage(self, payload, isBinary):

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':
    factory = WebSocketClientFactory("ws://")
    factory.protocol = MyClientProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_connection(factory, '', 80)

Further to what om26er suggests, if you truly want a “synchronous” API there is the “Crochet” library available for Twisted; see for more. This allows you to treat async Twisted calls as synchronous.