WebSocket Client
The datadivr client provides a simple interface for connecting to a WebSocket server and handling real-time communication.
Basic Usage
import asyncio
from datadivr import WebSocketClient, HandlerType, websocket_handler, WebSocketMessage
from typing import Optional
# Define handlers
@websocket_handler("sum_handler_result", HandlerType.CLIENT)
async def handle_sum_result(message: WebSocketMessage) -> None:
"""Handle the result of a sum calculation."""
print(f"Sum result from {message.from_id}: {message.payload}")
@websocket_handler("msg", HandlerType.CLIENT)
async def msg_handler(message: WebSocketMessage) -> None:
"""Handle text messages."""
print(f">> {message.from_id}: '{message.message}'")
# Create and run client
async def run_client() -> None:
# Create and connect client
client = WebSocketClient("ws://localhost:8765/ws")
await client.connect()
# Send a calculation request
await client.send_message(
payload={"numbers": [391, 29]},
event_name="sum_event"
)
# Create tasks for message handling
tasks = [
asyncio.create_task(client.receive_messages()),
]
try:
await asyncio.gather(*tasks)
finally:
for task in tasks:
task.cancel()
await client.disconnect()
# Run the client
asyncio.run(run_client())
Built-in Handlers
The client comes with several built-in handlers:
Sum Handler
@websocket_handler("sum_event_client", HandlerType.CLIENT)
async def sum_handler(message: WebSocketMessage) -> None:
"""Handle sum calculation results."""
print(f"Sum result from {message.from_id}: {message.payload}")
Message Handler
@websocket_handler("msg", HandlerType.CLIENT)
async def msg_handler(message: WebSocketMessage) -> None:
"""Handle text messages."""
print(f">> {message.from_id}({message.event_name}): '{message.message}'")
Interactive Usage
Here's how the CLI client uses these handlers:
async def run_client() -> None:
# Create and connect client
client = WebSocketClient(f"ws://{host}:{port}/ws")
await client.connect()
# Create tasks for message handling and user input
tasks = [
asyncio.create_task(client.receive_messages()),
asyncio.create_task(input_loop(client)),
]
try:
await asyncio.gather(*tasks)
finally:
for task in tasks:
task.cancel()
await client.disconnect()
# Example JSON messages to send:
# Sum calculation:
{"event_name": "sum_event", "payload": {"numbers": [391, 29]}}
# Broadcast message:
{"event_name": "msg", "to": "all", "message": "hello"}
Message Types
- Sum Calculation:
- Text Messages:
- Custom Events:
await client.send_message(
payload={"data": "custom_data"},
event_name="custom_event",
to="specific_client_id"
)
Error Handling
The client handles several error conditions:
NotConnectedError
: Raised when trying to send messages before connectingConnectionClosed
: Handled during message reception- Invalid message formats: Logged and handled gracefully
Connection Lifecycle
- Connection:
client = WebSocketClient("ws://localhost:8765/ws")
await client.connect() # Automatically registers handlers
- Message Loop:
- Disconnection:
Reference
datadivr.transport.client.WebSocketClient
A WebSocket client for communicating with a datadivr server.
This class handles the connection to a WebSocket server, message sending, and event handling for received messages.
Attributes:
Name | Type | Description |
---|---|---|
uri |
The WebSocket server URI to connect to |
|
handlers |
Dictionary of registered event handlers |
|
websocket |
WebSocketClientProtocol | None
|
The active WebSocket connection (if connected) |
Example
Source code in datadivr/transport/client.py
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 |
|
Functions
__init__(uri)
Initialize the WebSocket client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
uri
|
str
|
The WebSocket server URI to connect to |
required |
Source code in datadivr/transport/client.py
connect()
async
Connect to the WebSocket server and send initial handler information.
Source code in datadivr/transport/client.py
disconnect()
async
Close the WebSocket connection.
Source code in datadivr/transport/client.py
handle_event(event_data, websocket)
async
Handle an incoming event using registered handlers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_data
|
dict
|
The received event data |
required |
websocket
|
WebSocketClientProtocol
|
The WebSocket connection to use for responses |
required |
Source code in datadivr/transport/client.py
receive_messages()
async
Listen for incoming messages from the server.
Source code in datadivr/transport/client.py
send_handler_names()
async
Send a message with the names of all registered handlers.
This is called automatically after connection to inform the server about available client-side handlers.
Source code in datadivr/transport/client.py
send_message(payload, event_name, msg=None, to='others')
async
Send a message to the server.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload
|
Any
|
The message payload |
required |
event_name
|
str
|
The name of the event |
required |
msg
|
str | None
|
Optional text message |
None
|
to
|
str
|
The recipient of the message (default: "others") |
'others'
|
Raises:
Type | Description |
---|---|
NotConnectedError
|
If called before connecting to the server |
Source code in datadivr/transport/client.py
options: show_root_heading: true show_source: true