Aika da Karɓar Saƙonni WebSocket ta ciki Python

WebSocket sadarwa yana ba ka damar aikawa da karɓar saƙonnin ainihin lokaci tsakanin uwar garken da abokan ciniki. Anan ga cikakken jagora akan yadda ake cimma wannan ta Python amfani da websockets ɗakin karatu.

Mataki 1: Shigar da WebSocket Library

Da farko, shigar da websockets ɗakin karatu ta hanyar gudanar da umarni mai zuwa a cikin terminal:

pip install websockets

Mataki 2: Aika da Karɓar Saƙonni akan Sabar

A ƙasa akwai misalin yadda ake aikawa da karɓar saƙonni akan WebSocket sabar:

import asyncio  
import websockets  
  
# WebSocket connection handling function  
async def handle_connection(websocket, path):  
    async for message in websocket:  
        await websocket.send(f"Server received: {message}")  
  
# 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. Lokacin da abokin ciniki ya aika saƙo, wannan aikin yana saurare kuma ya aika da martani.

  • async for message in websocket:: Wannan madauki yana sauraron saƙonni daga abokin ciniki ta hanyar WebSocket haɗi.

  • await websocket.send(f"Server received: {message}"): Wannan aikin yana aika amsa daga uwar garken baya ga abokin ciniki ta hanyar WebSocket haɗin.

Mataki 3: Aika da Karɓar Saƙonni daga Abokin ciniki

Ga misalin yadda abokin ciniki ke aikawa da karɓar saƙonni daga WebSocket uwar garken:

import asyncio  
import websockets  
  
async def send_and_receive():  
    async with websockets.connect("ws://localhost:8765") as websocket:  
        await websocket.send("Hello, WebSocket!")  
        response = await websocket.recv()  
        print("Received:", response)  
  
asyncio.get_event_loop().run_until_complete(send_and_receive())  

A cikin snippet code:

  • async with websockets.connect("ws://localhost:8765") as websocket:: Wannan shine yadda abokin ciniki ke haɗawa zuwa WebSocket uwar garken. Abokin ciniki yana kafa haɗi zuwa localhost adireshin da tashar jiragen ruwa 8765.

  • await websocket.send("Hello, WebSocket!"): Abokin ciniki yana aika saƙon  zuwa uwar garken. Hello, WebSocket!

  • response = await websocket.recv(): Abokin ciniki yana jira don karɓar amsa daga uwar garken ta hanyar WebSocket haɗi.

Kammalawa

Ta bin matakai da fahimtar kowane ɓangaren misalin, kun sami nasarar koyon yadda ake aikawa da karɓar saƙonni ta WebSocket cikin Python. Wannan yana buɗe damar don ƙirƙirar aikace-aikacen lokaci-lokaci da ci gaba da musayar bayanai tsakanin uwar garken da abokan ciniki.