Home > Software engineering >  How to get response from blockchain.com by using wss in Python?
How to get response from blockchain.com by using wss in Python?

Time:12-12

I try to connect to blockchain.com websocket by using this API. I use websockets library for Python. When I connect by using the interactive client method, I have a success. But when I try to connect by using my Python script, I have no any response from server socket. This is my script:

import asyncio
import websockets


async def main():
    async with websockets.connect("wss://ws.blockchain.info/inv") as client:
        print(await client.recv())


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

This is what I have in terminal when I use interactive client, and I expect to see it when I run my script:

Connected to wss://ws.blockchain.info/inv.
>

CodePudding user response:

As @SteffenUllrich mentioned in comment this text is displayed by interactive client - it is not message received from server - and you have to use own print("Connected to wss://ws.blockchain.info/inv.") to display it.

And if you want to recv() something from sever then first you have to send() command to server.

import asyncio
import websockets

async def main():
    async with websockets.connect("wss://ws.blockchain.info/inv") as client:
        print("[main] Connected to wss://ws.blockchain.info/inv" )

        cmd = '{"op":"ping"}'
        print('[main] Send:', cmd)
        await client.send(cmd)
        print('[main] Recv:', await client.recv())

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Result:

[main] Connected to wss://ws.blockchain.info/inv
[main] Send: {"op":"ping"}
[main] Recv: {"op":"pong"}
  • Related