-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdemo_client.py
More file actions
164 lines (131 loc) · 5.55 KB
/
demo_client.py
File metadata and controls
164 lines (131 loc) · 5.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env python3
"""
standalone demo client for fasterpc testing
run this script to test the demo server
"""
import asyncio
import time
from fasterpc import rpc_methods_base, websocket_rpc_client, logging_config, LoggingModes
# configure logging
logging_config.set_mode(LoggingModes.UVICORN)
# client methods
class demo_client_methods(rpc_methods_base):
def __init__(self):
super().__init__()
self.notifications = []
async def receive_notification(self, message: str, data: dict):
"""receive notifications from server"""
notification = {
"message": message,
"data": data,
"timestamp": time.time()
}
self.notifications.append(notification)
print(f"📢 received notification: {notification}")
return {"status": "acknowledged"}
async def run_basic_tests():
"""run basic rpc tests"""
print("🧪 running basic rpc tests...")
async with websocket_rpc_client("ws://localhost:9000/ws", demo_client_methods()) as client:
# test echo
print("\n1️⃣ testing echo...")
response = await client.other.echo(message="hello fasterpc!")
print(f" echo response: {response.result}")
# test arithmetic
print("\n2️⃣ testing arithmetic...")
result = await client.other.add_numbers(a=15.5, b=25.3)
print(f" addition result: {result.result}")
# test server info
print("\n3️⃣ testing server info...")
info = await client.other.get_server_info()
print(f" server info: {info.result}")
# test data processing
print("\n4️⃣ testing data processing...")
test_data = {
"name": "test user",
"age": 25,
"preferences": ["python", "async", "websockets"]
}
processed = await client.other.process_data(data=test_data)
print(f" processed data: {processed.result}")
async def run_performance_test():
"""run performance test"""
print("\n⚡ running performance test...")
async with websocket_rpc_client("ws://localhost:9000/ws", demo_client_methods()) as client:
start_time = time.time()
iterations = 50
# concurrent calls
tasks = []
for i in range(iterations):
task = client.other.echo(message=f"performance_test_{i}")
tasks.append(task)
results = await asyncio.gather(*tasks)
end_time = time.time()
duration = end_time - start_time
calls_per_second = iterations / duration
print(f" completed {iterations} calls in {duration:.2f}s")
print(f" rate: {calls_per_second:.2f} calls/second")
# verify results
success_count = sum(1 for r in results if r.result == f"echo: performance_test_{results.index(r)}")
print(f" success rate: {success_count}/{iterations} ({success_count/iterations*100:.1f}%)")
async def run_error_test():
"""run error handling test"""
print("\n🚨 testing error handling...")
async with websocket_rpc_client("ws://localhost:9000/ws", demo_client_methods()) as client:
# test with invalid data
try:
# this should work fine
result = await client.other.add_numbers(a=1, b=2)
print(f" ✅ valid call succeeded: {result.result}")
except Exception as e:
print(f" ❌ unexpected error: {e}")
# test connection resilience
print(" testing connection resilience...")
for i in range(5):
try:
result = await client.other.echo(message=f"resilience_test_{i}")
print(f" ✅ call {i+1} succeeded: {result.result}")
except Exception as e:
print(f" ❌ call {i+1} failed: {e}")
async def run_interactive_demo():
"""run interactive demo"""
print("\n🎮 starting interactive demo...")
print(" type 'quit' to exit, or enter a message to echo:")
async with websocket_rpc_client("ws://localhost:9000/ws", demo_client_methods()) as client:
while True:
try:
user_input = input(" > ").strip()
if user_input.lower() in ['quit', 'exit', 'q']:
print(" 👋 goodbye!")
break
if user_input:
response = await client.other.echo(message=user_input)
print(f" 📨 server: {response.result}")
except KeyboardInterrupt:
print("\n 👋 interrupted by user")
break
except Exception as e:
print(f" ❌ error: {e}")
async def main():
"""main demo function"""
print("🚀 fasterpc demo client")
print("=" * 40)
try:
# run basic tests
await run_basic_tests()
# run performance test
await run_performance_test()
# run error test
await run_error_test()
# run interactive demo
await run_interactive_demo()
print("\n✅ all tests completed successfully!")
except Exception as e:
print(f"\n❌ demo failed: {e}")
print(" make sure the demo server is running on ws://localhost:9000/ws")
raise
if __name__ == "__main__":
print("🌐 connecting to ws://localhost:9000/ws")
print(" make sure to start the demo server first with: python demo_server.py")
print()
asyncio.run(main())