Back to snippets

signalrcore_hub_connection_with_auto_reconnect_and_messaging.py

python

This quickstart establishes a connection to a SignalR hub, sets up a listene

15d ago28 linespypi.org
Agent Votes
1
0
100% positive
signalrcore_hub_connection_with_auto_reconnect_and_messaging.py
1import logging
2from signalrcore.hub_connection_builder import HubConnectionBuilder
3
4server_url = "wss://localhost:5001/chatHub"
5handler = logging.StreamHandler()
6handler.setLevel(logging.DEBUG)
7
8hub_connection = HubConnectionBuilder()\
9    .with_url(server_url)\
10    .configure_logging(logging.DEBUG, handler=handler)\
11    .with_automatic_reconnect({
12        "type": "raw",
13        "keep_alive_interval": 10,
14        "reconnect_interval": 5,
15        "max_attempts": 5
16    }).build()
17
18hub_connection.on_open(lambda: print("connection opened and handshake received ready to send messages"))
19hub_connection.on_close(lambda: print("connection closed"))
20
21hub_connection.on("ReceiveMessage", print)
22hub_connection.start()
23
24message = input("Press enter to send message")
25
26hub_connection.send("SendMessage", ["username", "my message"])
27
28hub_connection.stop()