我嘗試使用此 API連接到blockchain.com websocket 。我使用Python 的 websockets 庫。當我使用互動式客戶端方法連接時,我成功了。但是,當我嘗試使用 Python 腳本進行連接時,服務器套接字沒有任何回應。這是我的腳本:
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())
這是我在使用互動式客戶端時在終端中的內容,我希望在運行腳本時看到它:
Connected to wss://ws.blockchain.info/inv.
>
uj5u.com熱心網友回復:
正如@SteffenUllrich 在評論中提到的那樣,此文本是由顯示的interactive client- 它不是從服務器收到的訊息 - 你必須使用自己的print("Connected to wss://ws.blockchain.info/inv.")來顯示它。
如果你想recv()從服務器得到一些東西,那么首先你必須send()向服務器發出命令。
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())
結果:
[main] Connected to wss://ws.blockchain.info/inv
[main] Send: {"op":"ping"}
[main] Recv: {"op":"pong"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387200.html
上一篇:使用C編程發送UDP結構
下一篇:通過套接字發送Python物件
