antho
antho

Reputation: 638

Difference between websocket and websockets

I don't understand the difference between websocket (websocket client) and websockets. I would like to understand the difference to know which one uses to be optimal.

I have a code that seems to do the same thing.

import websockets
import asyncio
import json

async def capture_data():
    uri = "wss://www.bitmex.com/realtime?subscribe=instrument:XBTUSD"
    #uri = "wss://www.bitmex.com/realtime"
    async with websockets.connect(uri) as websocket:
        while True:
            data = await websocket.recv()
            data = json.loads(data)
            try :
                #print('\n', data['data'][0]["lastPrice"])
                print('\n', data)
            except KeyError:
                continue


asyncio.get_event_loop().run_until_complete(capture_data())
import websocket
import json

def on_open(ws):
    print("opened")

    auth_data = {
        'op': 'subscribe',
        'args': ['instrument:XBTUSD']
    }
    ws.send(json.dumps(auth_data))

def on_message(ws, message):
    message = json.loads(message)
    print(message)

def on_close(ws):
    print("closed connection")


socket = "wss://www.bitmex.com/realtime"                 
ws = websocket.WebSocketApp(socket, 
                            on_open=on_open, 
                            on_message=on_message,
                            on_close=on_close)     
ws.run_forever()

EDIT:

Is Python powerful enough to receive a lot of data via websocket? In times of high traffic, I could have thousands of messages per second and even tens of thousands for short periods of time.

I've seen a lot of things about Nodejs that might be better than python but I don't know js and even if I just copy code from the internet I'm not sure I wouldn't waste time if I have to send the data to my python script and then process it.

Upvotes: 22

Views: 15641

Answers (3)

drsxr
drsxr

Reputation: 109

So I had a lot of confusion about this as well. There are three libraries/packages that are being talked about.

  1. Websocket , the native python low-level protocol useful for advanced users building custom protocols on top of WebSocket or for building custom servers.
  2. Websocket-client, a client-side only app from which you can use .WebSocketApp is a mid-level library with a simplified API for working with WebSocket clients. It is easier to use than websocket and a separate pip install.
  3. Websockets , with an 's', which is a higher level library built around asyncio that provides both client and server implementations of the WebSocket protocol. It is the most modern and feature-rich and is a good choice if you need asyncio support or advanced features like SSL/TLS encryption, compression, or per-message deflate.

Websocket does not play well with asyncio; one would presume Websocket-client might be the same (no info I can find), but Websockets is built around it.

Presumably you are asking about streaming data (video, music, financial) coming from the websocket - You'll just have to try it but I would anticipate financial data would be the easiest unless you are trying to load all symbols and all quotes from an exchange on a nanosecond scale which might be a bit much. Try it out and see what the practical limitations are and consider filtering.

Upvotes: 10

Giorgio Robino
Giorgio Robino

Reputation: 2265

websockets is a Python standard libary, currently suggested to use.

As far as I understand the main difference, from the client API programming, is that websocket-client support callbacks programming paradigm, in a way similar of javascript web client APIs.

Read the websockets documentation FAQs:

Are there onopen, onmessage, onerror, and onclose callbacks?

No, there aren’t.

websockets provides high-level, coroutine-based APIs. Compared to callbacks, coroutines make it easier to manage control flow in concurrent code.

If you prefer callback-based APIs, you should use another library.

With current Python 3 release the common / suggested way to manage asyncronous coroutines is via asyncio (used by websockets standard library approach).

So, answering your last question (Python vs nodejs), asyncio just allows to manage asyncronous I/O (networking-based in this case) events, as NodeJs does natively. broadley speaking, using asyncio you can achieve I/O websockets performances similar to that obtained using Nodejs.

Upvotes: 1

Peter Trcka
Peter Trcka

Reputation: 1521

websocket-client implements only client-side. If you want to create a WebSocket Server you have to use websockets.

websocket-client implements WebSocketApp which is more JavaScript like implementation of websocket.

I prefer WebSocketApp run as thread:

socket = "wss://www.bitmex.com/realtime"                 
ws = websocket.WebSocketApp(socket, 
                            on_open=on_open, 
                            on_message=on_message,
                            on_close=on_close) 

wst = threading.Thread(target=lambda: ws.run_forever())
wst.daemon = True
wst.start()

# your code continues here ...

Now you have asynchronous WebSocket. Your mainframe program is running and every time, when you receive the message, function on_message is called. on_message process the message automatically, without mainframe interruption.

Upvotes: 5

Related Questions