WebSocket yarjejeniya ce da ke ba da damar sadarwa ta hanyoyi biyu tsakanin uwar garken da abokin ciniki akan ci gaba da haɗin gwiwa. A cikin wannan labarin, za mu fara da sanin WebSocket a cikin Python.
Sanya WebSocket Laburare
Da fari dai, kuna buƙatar shigar da WebSocket ɗakin karatu da ya dace. Wasu shahararrun ɗakunan karatu sun haɗa da websockets
, websocket-client
, da autobahn
.
pip install websockets
Ƙirƙirar Sabar Mai WebSocket Sauƙi
Bari mu fara da ƙirƙirar WebSocket uwar garken mai sauƙi. A ƙasa akwai misali ta amfani da websockets
ɗakin karatu:
import asyncio
import websockets
async def handle_client(websocket, path):
async for message in websocket:
await websocket.send("You said: " + message)
start_server = websockets.serve(handle_client, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ƙirƙirar WebSocket Haɗin kai daga Abokin ciniki
Da zarar an saita uwar garken, zaku iya kafa WebSocket haɗi daga abokin ciniki:
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
await websocket.send("Hello, WebSocket!")
response = await websocket.recv()
print(response)
asyncio.get_event_loop().run_until_complete(hello())
Ta bin waɗannan matakai masu sauƙi, kun ɗauki mataki na gaba don sabawa WebSocket a cikin Python. Ci gaba da bincike da gina aikace-aikace masu ban sha'awa ta amfani da wannan ka'ida mai ƙarfi!