Fixed bug that could cause connection to close prematurely.

Also fixes proper exiting from xbmc.