WebSocket fasaha ce da ke ba da damar ingantacciyar watsa bayanai tsakanin uwar garken da abokan ciniki ta hanyar haɗin kai biyu. Anan ga jagora kan yadda ake amfani da shi WebSocket don watsa bayanan ainihin lokaci daga sabar zuwa abokan ciniki a Python:
Shigar da WebSocket Laburare
Yi amfani da websockets
ɗakin karatu don aiwatar da WebSocket uwar garken da abokin ciniki. Shigar da wannan ɗakin karatu ta amfani da pip:
pip install websockets
Gina WebSocket Sabar
Sabar WebSocket za ta aika bayanan ainihin-lokaci zuwa duk abokan cinikin da aka haɗa.
import asyncio
import websockets
# Function to send real-time data from the server
async def send_real_time_data(websocket, path):
while True:
real_time_data = get_real_time_data() # Get real-time data from a source
await websocket.send(real_time_data)
await asyncio.sleep(1) # Send data every second
start_server = websockets.serve(send_real_time_data, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
WebSocket Gina Abokin Ciniki
Abokin WebSocket ciniki zai saurare kuma ya karbi bayanan lokaci-lokaci daga uwar garken.
import asyncio
import websockets
async def receive_real_time_data():
async with websockets.connect("ws://localhost:8765") as websocket:
while True:
real_time_data = await websocket.recv()
print("Received real-time data:", real_time_data)
asyncio.get_event_loop().run_until_complete(receive_real_time_data())
Gudanar da Aikace-aikacen
Gudu da WebSocket lambar uwar garken farko, sannan ku gudanar da WebSocket lambar abokin ciniki. Za ku ga ainihin bayanan da ake watsawa daga uwar garken kuma abokin ciniki ya ci gaba da karɓa.
Keɓancewa da Ƙara
Daga nan, za ku iya keɓancewa da tsawaita aikace-aikacenku ta ƙara fasali kamar su tantancewa, tace bayanai, tsara bayanai, da ƙari.
Ƙarshe:
Yin amfani WebSocket da watsa bayanai na ainihi daga uwar garken zuwa abokan ciniki a Python hanya ce mai ƙarfi don gina aikace-aikacen sadarwa na lokaci-lokaci da kuma goge bayanan da aka sabunta nan take.