Refactor socket creation to handle errors