socket reading and error handling improved