Is it possible to have a signal for when the user session expires?

I am trying to build a streaming app using websockets. I have a long leaved thread that listen for events. I would like to be able to kill the thread by closing the WebSocket when the user leaves the app, or refresh the page. Is there a way to end the thread gracefully by sending a signal based on user existing the app?