Skip to content

Commit a5c8943

Browse files
committed
Add asyncio & threading client & server examples.
They're convenient to tweak to reproduce issues.
1 parent 07dc564 commit a5c8943

File tree

4 files changed

+91
-0
lines changed

4 files changed

+91
-0
lines changed

example/asyncio/client.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/usr/bin/env python
2+
3+
"""Client example using the asyncio API."""
4+
5+
import asyncio
6+
7+
from websockets.asyncio.client import connect
8+
9+
10+
async def hello():
11+
async with connect("ws://localhost:8765") as websocket:
12+
name = input("What's your name? ")
13+
14+
await websocket.send(name)
15+
print(f">>> {name}")
16+
17+
greeting = await websocket.recv()
18+
print(f"<<< {greeting}")
19+
20+
21+
if __name__ == "__main__":
22+
asyncio.run(hello())

example/asyncio/server.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/usr/bin/env python
2+
3+
"""Server example using the asyncio API."""
4+
5+
import asyncio
6+
from websockets.asyncio.server import serve
7+
8+
9+
async def hello(websocket):
10+
name = await websocket.recv()
11+
print(f"<<< {name}")
12+
13+
greeting = f"Hello {name}!"
14+
15+
await websocket.send(greeting)
16+
print(f">>> {greeting}")
17+
18+
19+
async def main():
20+
async with serve(hello, "localhost", 8765) as server:
21+
await server.serve_forever()
22+
23+
24+
if __name__ == "__main__":
25+
asyncio.run(main())

example/sync/client.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#!/usr/bin/env python
2+
3+
"""Client example using the threading API."""
4+
5+
from websockets.sync.client import connect
6+
7+
8+
def hello():
9+
with connect("ws://localhost:8765") as websocket:
10+
name = input("What's your name? ")
11+
12+
websocket.send(name)
13+
print(f">>> {name}")
14+
15+
greeting = websocket.recv()
16+
print(f"<<< {greeting}")
17+
18+
19+
if __name__ == "__main__":
20+
hello()

example/sync/server.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python
2+
3+
"""Server example using the threading API."""
4+
5+
from websockets.sync.server import serve
6+
7+
8+
def hello(websocket):
9+
name = websocket.recv()
10+
print(f"<<< {name}")
11+
12+
greeting = f"Hello {name}!"
13+
14+
websocket.send(greeting)
15+
print(f">>> {greeting}")
16+
17+
18+
def main():
19+
with serve(hello, "localhost", 8765) as server:
20+
server.serve_forever()
21+
22+
23+
if __name__ == "__main__":
24+
main()

0 commit comments

Comments
 (0)