Ngirim lan Nampa Pesen liwat WebSocket ing Python

WebSocket komunikasi ngijini sampeyan kanggo ngirim lan nampa pesen nyata-wektu antarane server lan klien. Mangkene pandhuan rinci babagan carane entuk iki kanthi Python nggunakake websockets perpustakaan.

Langkah 1: Instal WebSocket Pustaka

Pisanan, instal websockets perpustakaan kanthi nglakokake printah ing ngisor iki ing terminal:

pip install websockets

Langkah 2: Ngirim lan Nampa Pesen ing Server

Ing ngisor iki conto carane ngirim lan nampa pesen ing WebSocket server:

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

Ing potongan kode:

  • async def handle_connection(websocket, path):: Fungsi iki nangani WebSocket sambungan. Nalika klien ngirim pesen, fungsi iki ngrungokake lan ngirim respon maneh.

  • async for message in websocket:: Daur ulang iki ngrungokake pesen saka klien liwat WebSocket sambungan.

  • await websocket.send(f"Server received: {message}"): Fungsi iki ngirim respon saka server bali menyang klien liwat WebSocket sambungan.

Langkah 3: Ngirim lan Nampa Pesen saka Klien

Mangkene conto carane klien ngirim lan nampa pesen saka WebSocket server:

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

Ing potongan kode:

  • async with websockets.connect("ws://localhost:8765") as websocket:: Iki carane klien nyambung menyang WebSocket server. Klien nggawe sambungan menyang localhost alamat lan port 8765.

  • await websocket.send("Hello, WebSocket!"): Klien ngirim pesen  menyang server. Hello, WebSocket!

  • response = await websocket.recv(): Klien ngenteni nampa respon saka server liwat WebSocket sambungan.

Kesimpulan

Kanthi ngetutake langkah-langkah lan mangerteni saben bagean saka conto, sampeyan wis kasil sinau carane ngirim lan nampa pesen liwat WebSocket ing Python. Iki mbukak kemungkinan kanggo nggawe aplikasi wektu nyata lan ijol-ijolan data sing terus-terusan antarane server lan klien.