Fix potential memory leak, and socket doesn't disconnect properly