private void ProcessConnection(TcpClient tcpClient)
        {
            byte[]        buffer = new byte[4];
            NetworkStream stream = tcpClient.GetStream();

            stream.ReadTimeout       = kSocketReadTimeoutMillis;
            tcpClient.ReceiveTimeout = kSocketReadTimeoutMillis;
            while (!shouldStop)
            {
                int bytesRead = blockingRead(stream, buffer, 0, 4);
                if (bytesRead < 4)
                {
                    // Caught by phoneEventSocketLoop.
                    throw new Exception(
                              "Failed to read from controller emulator app event socket." +
                              "\nVerify that the controller emulator app is running.");
                }

                int msgLen = unpack32bits(correctEndianness(buffer), 0);

                byte[] dataBuffer = new byte[msgLen];
                bytesRead = blockingRead(stream, dataBuffer, 0, msgLen);
                if (bytesRead < msgLen)
                {
                    // Caught by phoneEventSocketLoop.
                    throw new Exception(
                              "Failed to read from controller emulator app event socket." +
                              "\nVerify that the controller emulator app is running.");
                }

                PhoneEvent proto =
                    PhoneEvent.CreateBuilder().MergeFrom(dataBuffer).Build();
                phoneRemote.OnPhoneEvent(proto);

                connected = EmulatorClientSocketConnectionState.Connected;

                if (!lastConnectionAttemptWasSuccessful)
                {
                    Debug.Log("Successfully connected to controller emulator app.");

                    // Log first failure after after successful read from event socket.
                    lastConnectionAttemptWasSuccessful = true;
                }
            }
        }
        private void phoneConnect()
        {
            string addr = EmulatorConfig.Instance.PHONE_EVENT_MODE == EmulatorConfig.Mode.USB
        ? EmulatorConfig.USB_SERVER_IP : EmulatorConfig.WIFI_SERVER_IP;

            try {
                if (EmulatorConfig.Instance.PHONE_EVENT_MODE == EmulatorConfig.Mode.USB)
                {
                    setupPortForwarding(kPhoneEventPort);
                }
                TcpClient tcpClient = new TcpClient(addr, kPhoneEventPort);
                connected = EmulatorClientSocketConnectionState.Connecting;
                ProcessConnection(tcpClient);
                tcpClient.Close();
            } finally {
                connected = EmulatorClientSocketConnectionState.Disconnected;
            }
        }