question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to know if client is connected?

See original GitHub issue

I’m using hbmqtt v0.9.0. My program, as an MQTT client, sometimes gets “Disconnected from broker” log and no longer receive new data from Mosquitto broker. I’m using default config (with auto-reconnect).

I have questions:

  • Does “auto-reconnect” work when connection is lost, while waiting for message in deliver_message()?
  • Any way to check if client is connected, so that I can call reconnect() and subscribe again?

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
stas-dubrovskyicommented, Sep 26, 2019
class MockedMQTTClient(MQTTClient):
    @asyncio.coroutine
    def handle_connection_close(self):

        def cancel_tasks():
            self._no_more_connections.set()
            while self.client_tasks:
                task = self.client_tasks.popleft()
                if not task.done():
                    task.set_exception(ClientException("Connection lost"))

        self.logger.debug("Watch broker disconnection")
        # Wait for disconnection from broker (like connection lost)
        yield from self._handler.wait_disconnect()
        self.logger.warning("Disconnected from broker")

        # Block client API
        self._connected_state.clear()

        # stop an clean handler
        #yield from self._handler.stop()
        self._handler.detach()
        self.session.transitions.disconnect()

        if hasattr(self, 'on_connection_close'):
            if inspect.iscoroutinefunction(self.on_connection_close):
                yield from self.on_connection_close()
            else:
                self.on_connection_close()

        if self.config.get('auto_reconnect', False):
            # Try reconnection
            self.logger.debug("Auto-reconnecting")
            try:
                yield from self.reconnect()
            except ConnectException:
                # Cancel client pending tasks
                cancel_tasks()
        else:
            # Cancel client pending tasks
            cancel_tasks()

    def set_close_callback(self, callback):
        self.on_connection_close = callback

Have done for myself in this dirty way.

If some kind of callback`s applicable for current project. I’m glad to prepare PR

0reactions
Equidamoidcommented, Mar 4, 2021

Yeah, looks like the only way is to not use the broken reconnect functionality:


    async def process_messages(self):
        while True:
            try:
                await self._cli.reconnect()
                await self._cli.subscribe([...])
                while True:
                    msg: hbmqtt.session.ApplicationMessage = await self._cli.deliver_message()
                    if not msg:
                        logger.warning("No message. Disconnected?")
                        raise RuntimeError('Disconnected?')
                    do_stuff(msg)
            except KeyboardInterrupt:
                raise
            except:
                logger.exception("whoops")
                await asyncio.sleep(5)

dirty but works

Read more comments on GitHub >

github_iconTop Results From Across the Web

How does a server know that a client is connected to it or not?
A server on its own may or may not have to.. An application (using the appropriate communication stack) may know if it is...
Read more >
Check client connection and connection/session takeover - IBM
The check is performed by sending a Timemark to each existing connection. The new connection is delayed early in the connection negotiation until...
Read more >
c - How to know if a new client is connecting to a socket with ...
Example : I have two clients set on fd user1 (fd = 4) and user2 (fd = 5). So, I use select to...
Read more >
How to check if same client is reconnected in client socket
When the Socket connect to clients, it has two pasts information, IP and port. You compare IP first to make sure whether it...
Read more >
Client API - Socket.IO
forceNew <boolean> whether to create a new connection ... To understand what happens under the hood, the following example:.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found