How do I detect when the preview window / application is closed?

I need to kill the socket connection when I develop and close the preview window but the editor hands that socket connection until I close the editor itself.

I would like a way to detect when the window is closed, regardless of the editor, so I create a socket connection each time I run/test it.

Thanks!