Refactor networking code