def test_reconnect_interval_config(self): connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl": False})\ .configure_logging(logging.ERROR)\ .with_automatic_reconnect({ "type": "interval", "intervals": [1, 2, 4, 45, 6, 7, 8, 9, 10] })\ .build() _lock = threading.Lock() connection.on_open(lambda: _lock.release()) connection.on_close(lambda: _lock.release()) self.assertTrue(_lock.acquire(timeout=30)) connection.start() self.assertTrue(_lock.acquire(timeout=30)) connection.stop() self.assertTrue(_lock.acquire(timeout=30)) _lock.release() del _lock
class TestSendAuthErrorMethod(BaseTestCase): server_url = Urls.server_url_ssl_auth login_url = Urls.login_url_ssl email = "test" password = "******" received = False message = None def login(self): response = requests.post(self.login_url, json={ "username": self.email, "password": self.password }, verify=False) if response.status_code == 200: return response.json()["token"] raise requests.exceptions.ConnectionError() def setUp(self): pass def test_send(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "access_token_factory": self.login, })\ .configure_logging(logging.ERROR)\ .build() self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.assertRaises(requests.exceptions.ConnectionError, lambda: self.connection.start())
class TestSendMethod(unittest.TestCase): container_id = "netcore_stream_app" connection = None server_url = "ws://localhost:82/streamHub" received = False connected = False items = list(range(0, 10)) def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url)\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 })\ .build() self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.connection.start() while not self.connected: time.sleep(0.1) def tearDown(self): self.connection.stop() def on_open(self): print("opene") self.connected = True def on_close(self): self.connected = False def on_complete(self, x): self.complete = True def on_error(self, x): pass def on_next(self, x): item = self.items[0] self.items = self.items[1:] self.assertEqual(x, item) def test_stream(self): self.complete = False self.items = list(range(0, 10)) self.connection.stream("Counter", [len(self.items), 500]).subscribe({ "next": self.on_next, "complete": self.on_complete, "error": self.on_error }) while not self.complete: time.sleep(0.1)
def __init__(self): super().__init__() self.hub_connection = HubConnectionBuilder() \ .with_url(self.server_url) \ .configure_logging(logging.DEBUG) \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build()
class TestSendAuthMethod(BaseTestCase): server_url = Urls.server_url_ssl_auth login_url = Urls.login_url_ssl email = "test" password = "******" received = False message = None def login(self): response = requests.post(self.login_url, json={ "username": self.email, "password": self.password }, verify=False) return response.json()["token"] def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "access_token_factory": self.login, "headers": { "mycustomheader": "mycustomheadervalue" } })\ .configure_logging(logging.ERROR)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() self.connection.on("ReceiveMessage", self.receive_message) self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.connection.start() while not self.connected: time.sleep(0.1) def receive_message(self, args): self.assertEqual(args[0], self.message) self.received = True def test_send(self): self.message = "new message {0}".format(uuid.uuid4()) self.username = "******" time.sleep(1) self.received = False self.connection.send("SendMessage", [self.message]) while not self.received: time.sleep(0.1)
def initialize(self): chatHubUrl = "https://iobtweb.azurewebsites.net/chatHub" self.hub_connection = HubConnectionBuilder()\ .with_url(chatHubUrl)\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 60, "reconnect_interval": 30, "max_attempts": 5 }).build() self.hub_connection.on("ChatMessage", self.handle_receive_message) self.hub_connection.start()
def test_auth_configured(self): with self.assertRaises(TypeError): hub = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "headers": { "mycustomheader": "mycustomheadervalue" } }) hub.has_auth_configured = True hub.options["access_token_factory"] = "" conn = hub.build()
def test_send(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "access_token_factory": self.login, })\ .configure_logging(logging.ERROR)\ .build() self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.assertRaises(requests.exceptions.ConnectionError, lambda: self.connection.start())
class TestSendMethod(unittest.TestCase): container_id = "netcore_stream_app" connection = None server_url = "wss://localhost:5001/chatHub" received = False connected = False items = list(range(0,10)) def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl":False})\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 })\ .build() self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.connection.start() while not self.connected: time.sleep(0.1) def tearDown(self): self.connection.stop() def on_open(self): print("opene") self.connected = True def on_close(self): self.connected = False def on_complete(self, x): self.complete = True def on_error(self, x): pass def test_stream(self): self.complete = False self.items = list(range(0,10)) subject = Subject() self.connection.send("UploadStream", subject) while(len(self.items) > 0): subject.next(str(self.items.pop())) subject.complete() self.assertTrue(len(self.items) == 0)
def main(game_token=''): game = None user_token = None if game_token == '': game = Game('user1', game_token) user_token, game_token = game.start() game.game_token = game_token print(game_token) else: game = Game('user2', game_token) user_token = game.accept() hub_connection = HubConnectionBuilder().with_url( "ws://localhost:5000/engine", options={ "access_token_factory": lambda: user_token }).with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build().build() hub_connection.start() hub_connection.on("Shot", lambda _: game.shot()) hub_connection.on("Accepted", lambda _: game.accepted()) while True: command = input() if command.lower() == 'quit': print("Goodbye!") return if command.lower().startswith('shoot'): command = command.replace('shoot', '') (x, y) = list(map(int, command.split())) game.shoot(x, y)
def main(game_token=None): game = None user_token = None if game_token is None: game = Game(2, 'user1') user_token, game_token = game.start() print(game_token) else: game = Game(2, 'user2') user_token = game.accept(game_token) hub_connection = HubConnectionBuilder().with_url( "ws://localhost:5000/engine", options={ "access_token_factory": lambda: user_token }).build() hub_connection.start() hub_connection.on("Shot", lambda _: game.shot()) hub_connection.on("Accepted", lambda _: game.accepted()) while True: command = input() if command.lower() == 'quit': print("Goodbye!") return if command.lower().startswith('shoot'): command = command.replace('shoot', '') (x, y) = list(map(int, command.split())) game.shoot(x, y)
class SignalRConnector(BaseModule): connection: HubConnectionBuilder = None def __init__(self, hub_url): self.hub_url = hub_url def boot(self): logging.info("Connecting to websocket") self.connection = HubConnectionBuilder() \ .with_url(self.hub_url) \ .configure_logging(logging.DEBUG) \ .with_automatic_reconnect( { "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 } ) \ .build() self.connection.on_open(self.on_signalr_connected) self.connection.on_close(self.on_signalr_disconnected) self.connection.on('EventAdded', self.on_signalr_event) self.connection.start() self.subscribe(self.on_event) self.subscribe(self.handle_connected, types=SignalRConnected) def on_signalr_connected(self): self.publish(SignalRConnected('Anagon AI Bot')) def on_signalr_disconnected(self): self.publish(SignalRDisconnected('Anagon AI Bot')) def on_signalr_event(self, args): event, = args logging.info("Received SignalR event: %s" % event) if ('type', 'be.anagon.ai.signalr.connected') in event.items(): self.publish(SignalRConnected(event['client_name'])) pass def on_event(self, event: BaseEvent): logging.info("Passing event %s to SignalR server" % event) if not isinstance(event, SignalRConnected): self.connection.send('AddEvent', [event.as_dict]) def handle_connected(self, event: SignalRConnected): self.publish(TextOutput(text='%(client_name)s connected through SignalR' % event.as_dict))
def _start_signals(self): url = "https://api.easee.cloud/hubs/chargers" options = {"access_token_factory": self._get_access_token,"headers":{"APP":"no.easee.apps.bridge"}} self.signals = HubConnectionBuilder().with_url(url,options).configure_logging(logging.ERROR).with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 30, "reconnect_interval": 5, "max_attempts": 5 }).build() self.signals.on_open(lambda: self.on_open()) self.signals.on_close(lambda: self.on_close()) self.signals.on_error(lambda data: print(f"An exception was thrown closed{data.error}")) self.signals.on("ProductUpdate", self.product_update) self.signals.start()
def __init__(self, server, id): self.server_url = server self.ifcb_id = id self.handlers = {} self.next_handler_id = 0 self.hub_connection = ( HubConnectionBuilder() .with_url(self.server_url) .configure_logging(logging.CRITICAL) .with_automatic_reconnect( { "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5, } ) .build() ) self.hub_connection.on_open(self.on_connect) self.hub_connection.on("heartbeat", self.do_nothing) self.hub_connection.on("messageRelayed", self.handle_message) self.hub_connection.on("startedAsClient", self.started) self.hub_connection.on("disconnect", self.disconnect)
def __init__(self, settings: SignalRSettings): self.settings = settings self._callback: Optional[Callable[[PrintRequest], Any]] = None self._connected = False handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) self.connection: BaseHubConnection = HubConnectionBuilder() \ .with_url(self.settings.endpoint, options={"verify_ssl": self.settings.verify_ssl}) \ .with_automatic_reconnect({"type": "raw", "reconnect_interval": 10, "keep_alive_interval": 10}) \ .build() self.connection.on_open(self._on_connected) self.connection.on_close(self._on_disconnected) def handler(arguments): serial, mode_, payload = arguments mode = RequestMode(mode_) if mode == RequestMode.PNG: payload = base64.b64decode(payload) if self._callback: self._callback(PrintRequest(serial, mode, payload)) self.connection.on("SendPrintRequest", handler)
def setSensorHub(self): self._hub_connection = HubConnectionBuilder()\ .with_url(f"{self.HOST}/SensorHub?token={self.TOKEN}")\ .configure_logging(logging.INFO)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 999 }).build() self._hub_connection.on("ReceiveSensorData", self.onSensorDataReceived) self._hub_connection.on_open(lambda: print("||| Connection opened.")) self._hub_connection.on_close(lambda: print("||| Connection closed.")) self._hub_connection.on_error(lambda data: print( f"||| An exception was thrown closed: {data.error}"))
def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url)\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 })\ .build() self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.connection.start() while not self.connected: time.sleep(0.1)
def test_enable_trace(self): hub = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl":False})\ .configure_logging(logging.WARNING, socket_trace=True)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 })\ .build() hub.on_open(self.on_open) hub.on_close(self.on_close) hub.start() self.assertTrue(websocket.isEnabledForDebug()) websocket.enableTrace(False) hub.stop()
def __init__(self, request_processor): super(ConnectionHandler, self).__init__() self.request_processor = request_processor self.server_url = "wss://localhost:44385/computeHub" self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False })\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 15, "reconnect_interval": 5, "max_attempts": 5 }).build()
def __init__(self, threadID, name, counter): super().__init__() print(" SignalRCommands: __init__") self.hub_connection = HubConnectionBuilder() \ .with_url(self.server_url) \ .configure_logging(logging.DEBUG) \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }) \ .build() threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter
def _setUp(self, msgpack=False): builder = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "access_token_factory": self.login, "headers": { "mycustomheader": "mycustomheadervalue" } }) if msgpack: builder.with_hub_protocol(MessagePackHubProtocol()) builder.configure_logging(logging.WARNING)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }) self.connection = builder.build() self.connection.on("ReceiveMessage", self.receive_message) self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self._lock = threading.Lock() self.assertTrue(self._lock.acquire(timeout=30)) self.connection.start()
async def initialize(self): self.negotiate_request = await self.requests.get( url="https://realtime.roblox.com/notifications/negotiate" "?clientProtocol=1.5" "&connectionData=%5B%7B%22name%22%3A%22usernotificationhub%22%7D%5D", cookies=self.requests.session.cookies) self.wss_url = f"wss://realtime.roblox.com/notifications?transport=websockets" \ f"&connectionToken={quote(self.negotiate_request.json()['ConnectionToken'])}" \ f"&clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22usernotificationhub%22%7D%5D" self.connection = HubConnectionBuilder() self.connection.with_url( self.wss_url, options={ "headers": { "Cookie": f".ROBLOSECURITY={self.requests.session.cookies['.ROBLOSECURITY']};" }, "skip_negotiation": False }) def on_message(_self, raw_notification): """ Internal callback when a message is received. """ try: notification_json = json.loads(raw_notification) except json.decoder.JSONDecodeError: return if len(notification_json) > 0: notification = Notification(notification_json) self.evtloop.run_until_complete( self.on_notification(notification)) else: return self.connection.with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() self.connection.hub.on_message = on_message self.connection.start()
def start(self): if self.__hub is not None: print("game server: already started") return self.__hub = HubConnectionBuilder() \ .with_url(Settings().game_server_url + "/teamshub") \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, }) \ .build() self.__hub.on_open(self.__on_open) self.__hub.on_close(self.__on_close) self.__hub.on("RequestExecuteTurn", self.__on_request_execute_turn) self.__hub.on("ReceiveFinalMap", self.__on_receive_final_map) self.__hub.start()
def get_connection(self, msgpack=False): builder = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl":False})\ .configure_logging(logging.ERROR)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }) if msgpack: builder.with_hub_protocol(MessagePackHubProtocol()) hub = builder.build() hub.on_open(self.on_open) hub.on_close(self.on_close) return hub
def start(self): if self.__hub is not None: print("lhapi: already started") return self.__hub = HubConnectionBuilder() \ .with_url(Settings().lhapi_url + "/teamshub") \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, }) \ .build() self.__hub.on_open(self.__on_open) self.__hub.on_close(self.__on_close) self.__hub.on("AssignTeamId", self.__on_assign_team_id) self.__hub.on("AssignGameServerUriToGameId", self.__on_assign_game_server_uri_to_game_id) self.__hub.start()
def test_reconnect_interval(self): connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl": False})\ .configure_logging(logging.ERROR)\ .with_automatic_reconnect({ "type": "interval", "intervals": [1, 2, 4, 45, 6, 7, 8, 9, 10], "keep_alive_interval": 3 })\ .build() self.reconnect_test(connection)
def test_bad_auth_function(self): with self.assertRaises(TypeError): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "access_token_factory": 1234, "headers": { "mycustomheader": "mycustomheadervalue" } })
def test_raw_reconnection(self): connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl": False})\ .configure_logging(logging.ERROR)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "max_attempts": 4 })\ .build() self.reconnect_test(connection)
def start(self, name, server, port): """runs the client, communicating with the server as necessary""" self.name = name self.connection = HubConnectionBuilder().with_url( f"{server}:{port}/riskhub").build() self.connection.on(MessageTypes.ReceiveMessage, print) self.connection.on(MessageTypes.SendMessage, print) self.connection.on(MessageTypes.SendStatus, self.handle_status) self.connection.on(MessageTypes.JoinConfirmation, self.handle_join) self.connection.on(MessageTypes.YourTurnToDeploy, self.handle_deploy) self.connection.on(MessageTypes.YourTurnToAttack, self.handle_attack) self.connection.on_open(self.handle_open) self.connection.on_close(self.handle_close) self.connection.start() # accept commands (mostly just waiting while the server interupts) command = "" while (command.lower() != 'exit'): print("Please enter a command ('exit' to exit): ", end="") command = input()
def create_hub_connection(context): hub_connection = HubConnectionBuilder()\ .with_url(read_secret("hub_url"), options={ "access_token_factory": login })\ .configure_logging(logging.DEBUG)\ .build() hub_connection.on_open( lambda: logging.info(f"{context} signalR connection is now open")) hub_connection.on_close( lambda: logging.info(f"{context} signalR connection is now closed")) hub_connection.on_error(lambda data: logging.warning( f"{context} an exception was thrown: '{data.error}'")) return hub_connection