refactored opensocket function