Changed disconnect code so that the thread stops fully before the socket is closed. This was causing me problems as the thread often went around the loop one more time after the socket closed.