added better error detection, fixed not closing sockets