Search code examples
atmosphere

What is the correct way to add an EventListener to an AtmosphereResource?


I am using Atmosphere Framework 2.0.8.

I have implemented an AtmosphereHandler in my application and have two way communication occurring correctly over WebSockets and Long Polling.

I am trying to add some handling code for when the client disconnects to clean up some resources specific to that client (ie. I have an entry in a table I want to remove).

I have read the following wiki entries:

OnDisconnect Tricks: https://github.com/Atmosphere/atmosphere/wiki/onDisconnect-tricks Configuring Atmosphere Listener: https://github.com/Atmosphere/atmosphere/wiki/Configuring-Atmosphere-Listener

The thing I am not clear on is where I should add the call to

atmosphereResource.addEventListener( new AtmosphereResourceEventListenerAdapter() {} );

I eventually found some example code in the JavaDoc for the AtmosphereHandler that registers the EventListener in the onRequest() method. http://atmosphere.github.io/atmosphere/apidocs/org/atmosphere/cpr/AtmosphereHandler.html

What I would like to know is if this is the correct way to go about it?

It is my understanding that the AtmosphereResource represents the connection between a client and the server for the life of that connection. The uuid stays consistent for the object on multiple calls through the onRequest() method from the same client. As such, the same AtmosphereResource object will get the EventListener added every time the onRequest method is called.

This seems wrong. Wouldn't this lead to thousands of EventListeners being registered for each AtmosphereResource?

It seems that the EventLister should only be registered once for each AtmosphereResource.

I feel like I am missing something fundamental here. Could someone please explain?


Solution

  • Here's an example using MeteorServlet, so it won't look exactly like what you'll have to do, but it should get you started. I add the listener to a Meteor instance, and you'll add yours to an AtmosphereResource. Each resource gets just one listener.

    The overridden onDisconnect() method calls this Grails service method that handles the event. Of course, you'll want to call something that cleans up your database resource.

    Note that the servlet is configured using these options. I think you might need the org.atmosphere.interceptor.HeartbeatInterceptor, but it's been so long since I initially set it up, I can't remember if it's necessary.