Miwiti karo WebSocket ing Python

WebSocket minangka protokol sing ngidini komunikasi rong arah antarane server lan klien liwat sambungan sing terus-terusan. Ing artikel iki, kita bakal miwiti karo kenalan karo WebSocket ing Python.

Nginstal WebSocket Pustaka

Kaping pisanan, sampeyan kudu nginstal WebSocket perpustakaan sing cocog. Sawetara perpustakaan populer kalebu websockets, websocket-client, lan autobahn.

pip install websockets

WebSocket Nggawe Server Prasaja

Ayo dadi miwiti nggawe WebSocket server prasaja. Ing ngisor iki conto nggunakake websockets perpustakaan:

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()  

Nggawe WebSocket Sambungan saka Klien

Sawise server disetel, sampeyan bisa nggawe WebSocket sambungan saka klien:

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())  

Kanthi ngetutake langkah-langkah prasaja iki, sampeyan wis njupuk langkah luwih dhisik kanggo kenalan karo WebSocket ing Python. Terusake njelajah lan mbangun aplikasi sing nyenengake nggunakake protokol sing kuat iki!