WebSocket huwa protokoll li jippermetti komunikazzjoni f'żewġ direzzjonijiet bejn server u klijent fuq konnessjoni kontinwa. F'dan l-artikolu, se nibdew billi nsiru familjari ma WebSocket ' fi Python.
Installazzjoni WebSocket tal-Librerija
L-ewwelnett, għandek bżonn tinstalla l- WebSocket librerija xierqa. Xi libreriji popolari jinkludu websockets
, websocket-client
, u autobahn
.
pip install websockets
WebSocket Ħolqien ta ' Server Sempliċi
Nibdew billi noħolqu WebSocket server sempliċi. Hawn taħt hawn eżempju bl-użu tal- websockets
librerija:
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()
Stabbiliment ta WebSocket 'Konnessjoni mill-Klijent
Ladarba s-server jiġi stabbilit, tista' tistabbilixxi WebSocket konnessjoni mill-klijent:
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())
Billi ssegwi dawn il-passi sempliċi, ħadt pass ieħor biex tiffamiljarizza ruħek WebSocket ma' Python. Kompli esplora u tibni applikazzjonijiet eċċitanti billi tuża dan il-protokoll qawwi!