WebSocket में शुरुआत करना Python

WebSocket एक प्रोटोकॉल है जो एक सर्वर और क्लाइंट के बीच निरंतर कनेक्शन पर दो-तरफ़ा संचार सक्षम बनाता है। WebSocket इस लेख में, हम इससे परिचित होकर शुरुआत करेंगे Python ।

WebSocket लाइब्रेरी स्थापित करना

सबसे पहले, आपको उपयुक्त WebSocket लाइब्रेरी स्थापित करने की आवश्यकता है। कुछ लोकप्रिय पुस्तकालयों में websockets, websocket-client, और शामिल हैं autobahn ।

pip install websockets

WebSocket एक साधारण सर्वर बनाना

आइए एक सरल WebSocket सर्वर बनाकर शुरुआत करें। लाइब्रेरी का उपयोग करने का एक उदाहरण नीचे दिया गया है websockets:

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

WebSocket क्लाइंट से कनेक्शन स्थापित करना

एक बार सर्वर सेट हो जाने पर, आप WebSocket क्लाइंट से कनेक्शन स्थापित कर सकते हैं:

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

इन सरल चरणों का पालन करके, आप इससे परिचित होने की दिशा में एक कदम आगे बढ़ गए WebSocket हैं Python । इस शक्तिशाली प्रोटोकॉल का उपयोग करके रोमांचक अनुप्रयोगों की खोज और निर्माण जारी रखें!