Fixed hanging due to socket error

Fixed hang due to unhandled socket errors like connection reset, etc.
The new code generates an exception which may be fatal to apps using this library.
I think this PR needs some testing before merging.