Added proper error handling to socket code