在制定交易策略之前,通常需要从 cex websocket 接口检索数据。因此,采用优秀的 websocket 数据检索解决方案至关重要。本文将比较两种不同的 websocket 客户端实现。
协程和回调的区别
协程
在 websocket 的上下文中,可以利用协程来有效地处理异步任务。例如,可以采用异步协程以非阻塞方式管理传入消息。以下是设置服务器的简单代码示例:
设置服务器的代码示例:
#!/usr/bin/env python
import asyncio
import websockets
# the websocket parameter is an instance of the WebSocketServerProtocol class,
# and it represents the communication channel between the server and
# a specific client connected to the WebSocket server
async def handler(websocket):
while True:
message = await websocket.recv()
print(message)
# Send the same message back to the client
await websocket.send(f"Server echoing: {message}")
# will be called each time a new client connects to the server
async def main():
# "" represents loopback interface that allows
# communication between processes on the same device.
async with websockets.serve(handler, "", 8001):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
客户端代码:
import asyncio
import websockets
async def connect_to_server():
uri = "ws://localhost:8001" # Change the URI to match your server address
async with websockets.connect(uri) as websocket:
while True:
message = input("Enter a message to send to the server (or 'exit' to quit): ")
if message.lower() == 'exit':
break
await websocket.send(message)
# Receive and print the echoed message from the server
response = await websocket.recv()
print(f"Received from server: {response}")
if __name__ == "__main__":
asyncio.run(connect_to_server())
回调
在 websockets 领域,回调可用于定义在特定事件(如接收消息、建立连接或遇到错误)发生时执行的函数。现在让我们使用回调方案重写客户端代码:
import websocket
def on_message(ws, message):
print(f"Received from server: {message}")
def connect_to_server():
uri = "ws://localhost:8001" # Change the URI to match your server address
ws = websocket.WebSocketApp(uri, on_message=on_message)
while True:
user_input = input("Enter a message to send to the server (or 'exit' to quit): ")
if user_input.lower() == 'exit':
break
ws.send(user_input)
ws.close()
if __name__ == "__main__":
connect_to_server()
区别
回调在较旧的异步代码中很普遍,并且可以在严重依赖事件驱动架构的系统中使用。另一方面,协程是现代 Python 异步编程的首选方法,尤其是引入了 async/await 语法后。
我喜欢协程方案主要是因为它为异步编程提供了更优雅、更易读的解决方案,使其成为现代 Python 开发中的首选方法。
作者:0xCryptoQuant
本文来自作者投稿,版权归原作者所有。如需转载,请注明出处:https://www.nxrte.com/jishu/im/38196.html