Back

Realtime 'on connection break'

  • 0
  • Realtime
nightwielder
22 Jun, 2023, 18:19

Hey! I'd like to know when a user disconnects. Something like this, for example:

TypeScript
client.onRealtimeConnectionLost(() => {
  databases.createDocument('main', 'messages', {message: `${currentUser.name} has left the game.`});

I hope my question is clear. Is it possible? If not, could you suggest some efficient workarounds? Thanks!

TL;DR
The user wants to know if another user is on the same page in real-time. One solution is to use a presence collection with user IDs and page information. When a user is on the page, a document is created and updated. After a period of inactivity, the document is deleted. The real-time feature listens for changes in the presence collection. A workaround for now is to implement a heartbeat/pinging approach where the client sends a request at a certain interval to let the server know it's still active. If there's no response within a certain time, the server can determine that the user has disconnected.
Drake
22 Jun, 2023, 18:27

You might want to πŸ‘πŸΌ this issue: https://github.com/appwrite/appwrite/issues/2418

For now, you can implement a heartbeat/pinging approach where the client sends a request every X interval to let the server know it's still around. After Y interval of no responses, the server would determine the user has left/disconnected

nightwielder
22 Jun, 2023, 18:33

Thanks!

nightwielder
22 Jun, 2023, 18:58

Um could you help me a bit more? Basically, a user needs to know if another user is on the same page. Let's say I wrote an interval function that keeps pinging they're on that page but in what way? I could have a collection for this. With documents like pageId = {currentlyPresent=["userId1", "userId2"]} etc and then subscribe to that particular document to get realtime update. But how do I actually detect there are two users concurrently on that page? I'm sorry if I'm not making any sense but I hope you at least understand what I need.

Drake
22 Jun, 2023, 19:08

you could have a presence collection with userId and page. when a user is on the page, a document will be created. the document will be updated as long as they're on the page. after inactivity, the document would be deleted.

The realtime would listen for documents in that collection and then do as needed

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more