apocalypsis
apocalypsis

Reputation: 571

WebSocketApp vs create_connection

I was wondering if someone could explain the difference between:

ws = websocket.create_connection('wss://echo.websocket.org')

and

ws = websocket.WebSocketApp('wss://echo.websocket.org')

within the Python package websocket, as the docs aren't very clear.

Upvotes: 3

Views: 2726

Answers (1)

Chris Hunt
Chris Hunt

Reputation: 4030

create_connection is a factory function that generates a websocket class from the one provided in the class_ keyword argument, websocket.WebSocket by default. This class provides low-level interface but can be used directly for code that just needs to interact with the websocket imperatively - send message, wait for response, send next message - and so on.

WebSocketApp is a wrapper around WebSocket that provides a more 'event-driven' interface. You provide callbacks to the constructor (or by assignment to the relevant members after initialization), then call run_forever which blocks until the connection is closed. When messages come, the WebSocketApp calls your callback functions. This could drive your whole app, or you could call run_forever in a different thread and do other work at the same time (such as updating game state periodically based on a timer instead of only when messages are received).

Upvotes: 10

Related Questions