Gina WebSocket uwar garken a ciki Python yana ba ku damar kafa tashar sadarwa mai ci gaba da bi-directional tsakanin uwar garken da abokan ciniki. A ƙasa akwai cikakken jagorar da ke bayanin kowane bangare don gina WebSocket sabar asali ta amfani da websockets
ɗakin karatu.
Mataki 1: Shigar da WebSocket Library
Don farawa, kuna buƙatar shigar da websockets
ɗakin karatu ta hanyar aiwatar da umarni mai zuwa a cikin terminal:
pip install websockets
Mataki 2: Ƙirƙirar WebSocket uwar garken
Ga misalin yadda ake gina WebSocket uwar garken a cikin Python:
import asyncio
import websockets
# WebSocket connection handling function
async def handle_connection(websocket, path):
async for message in websocket:
# Process the data and send a response
response = f"Server received: {message}"
await websocket.send(response)
# Initialize the WebSocket server
start_server = websockets.serve(handle_connection, "localhost", 8765)
# Run the server within the event loop
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
A cikin snippet code:
-
async def handle_connection(websocket, path):
: Wannan aikin yana ɗaukar WebSocket haɗi. Duk lokacin da abokin ciniki ya haɗu, ana kiran wannan aikin don sarrafa sadarwa. -
async for message in websocket:
: Wannan madauki yana maimaita don sauraron saƙonni daga abokin ciniki ta hanyar WebSocket haɗin. -
await websocket.send(response)
: Wannan aikin yana aika amsa daga uwar garken baya ga abokin ciniki ta hanyar WebSocket haɗin. -
websockets.serve(handle_connection, "localhost", 8765)
: Wannan aikin yana ƙirƙirar WebSocket uwar garken da ke sauraron haɗi akanlocalhost
adireshi da tashar jiragen ruwa8765
.
Mataki 3: Gwada Sabar
Bayan ƙaddamar da lambar uwar garken, zai saurari haɗin kai daga abokan ciniki a tashar jiragen ruwa 8765. Kuna iya gwada uwar garken ta hanyar haɗawa da shi ta amfani da WebSocket lambar abokin ciniki ko kayan aikin gwaji na kan layi.
Kammalawa
Ta bin waɗannan matakan, kun sami nasarar gina WebSocket uwar garken mai sauƙi a cikin Python. Wannan uwar garken yana ba da tushe don ƙirƙirar aikace-aikace na ainihi da hulɗa tsakanin uwar garken da abokan ciniki ta amfani da WebSocket yarjejeniya.