File tree Expand file tree Collapse file tree
Misc/WebSockets/python-websockets Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1-
1+ # Importing the relevant libraries
22import websockets
33import asyncio
44
5- async def hello ():
6- url = "ws://127.0.0.1:7890"
7- async with websockets .connect (url ) as ws :
8- await ws .send ("Hello Server!" )
9-
10-
5+ # The main function that will handle connection and communication
6+ # with the server
117async def listen ():
128 url = "ws://127.0.0.1:7890"
13-
9+ # Connect to the server
1410 async with websockets .connect (url ) as ws :
11+ # Send a greeting message
12+ await ws .send ("Hello Server!" )
13+ # Stay alive forever, listening to incoming msgs
1514 while True :
1615 msg = await ws .recv ()
1716 print (msg )
1817
19- asyncio . get_event_loop (). run_until_complete ( hello ())
18+ # Start the connection
2019asyncio .get_event_loop ().run_until_complete (listen ())
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 1+ # Importing the relevant libraries
2+ import websockets
3+ import asyncio
4+
5+ PORT = 7890
6+
7+ print ("Server listening on Port " + str (PORT ))
8+
9+ async def echo (websocket , path ):
10+ print ("A client just connected" )
11+ try :
12+ async for message in websocket :
13+ print ("Received message from client: " + message )
14+ await websocket .send ("Pong: " + message )
15+ except websockets .exceptions .ConnectionClosed as e :
16+ print ("A client just disconnected" )
17+
18+ start_server = websockets .serve (echo , "localhost" , PORT )
19+
20+ asyncio .get_event_loop ().run_until_complete (start_server )
21+ asyncio .get_event_loop ().run_forever ()
22+
Original file line number Diff line number Diff line change 1+ # Importing the relevant libraries
2+ import websockets
3+ import asyncio
4+
5+ # Server data
6+ PORT = 7890
7+ print ("Server listening on Port " + str (PORT ))
8+
9+ # A set of connected ws clients
10+ connected = set ()
11+
12+ # The main behavior function for this server
13+ async def echo (websocket , path ):
14+ print ("A client just connected" )
15+ # Store a copy of the connected client
16+ connected .add (websocket )
17+ # Handle incoming messages
18+ try :
19+ async for message in websocket :
20+ print ("Received message from client: " + message )
21+ # Send a response to all connected clients except sender
22+ for conn in connected :
23+ if conn != websocket :
24+ await conn .send ("Someone said: " + message )
25+ # Handle disconnecting clients
26+ except websockets .exceptions .ConnectionClosed as e :
27+ print ("A client just disconnected" )
28+ finally :
29+ connected .remove (websocket )
30+
31+ # Start the server
32+ start_server = websockets .serve (echo , "localhost" , PORT )
33+ asyncio .get_event_loop ().run_until_complete (start_server )
34+ asyncio .get_event_loop ().run_forever ()
35+
You can’t perform that action at this time.
0 commit comments