Quick Start: Client
This walk-through connects a Python client to a SignalR hub, calls a server method, and reacts to server-initiated messages.
1. Create a connection
import asyncio
from aiosignalr.client import HubConnection
async def main() -> None:
connection = HubConnection()
await connection.start("http://127.0.0.1:8080/hub")
# ... use the connection ...
await connection.stop()
asyncio.run(main())
start() performs the POST /negotiate handshake, selects the best transport
and completes the protocol handshake before returning. By default the client
tries the transports in server-declared order (WebSocket → SSE → Long Polling).
2. Call a server method
Use invoke() to call a method and wait for its result:
result = await connection.invoke("Add", 40, 2)
print("Add(40, 2) =", result) # 42
Use send() for fire-and-forget calls (no result is expected):
await connection.send("Notify", "hello")
3. Stream results
Server methods that return an async iterator can be consumed with stream():
async for item in await connection.stream("Counter", 3):
print("stream item:", item)
4. Receive messages from the server
Register handlers with on(). When the server calls a method, every matching
handler runs with the arguments:
connection.on("message", lambda text: print("got:", text))
# An async handler is supported too.
async def on_joined(user: str) -> None:
print(f"{user} joined the room")
connection.on("userJoined", on_joined)
If a handler returns a non-None value, it is sent back to the server as the
invocation result (a client result).
5. Full example
import asyncio
from aiosignalr.client import HubConnection
async def main() -> None:
connection = HubConnection()
connection.on("message", lambda text: print("got:", text))
await connection.start("ws://127.0.0.1:8080/hub")
result = await connection.invoke("Add", 40, 2)
print("Add(40, 2) =", result)
async for item in await connection.stream("Counter", 3):
print("stream item:", item)
await connection.send("Notify", "hello")
await connection.stop()
asyncio.run(main())