1

我正在尝试使用TcpClient. 模拟器是在 localhost:5554 上运行的 Android 4.2.2,我从 AVD Manager 开始。我能够连接并发送“电源状态放电”命令,但在发送第二个命令后,程序挂起等待响应。当我使用 Putty 原始连接进行连接时,这些命令有效。

这是完整的代码:

using System;
using System.Net.Sockets;
using System.Text;

namespace AndroidBatteryChangeEmulator
{
    class Program
    {
        private static readonly TcpClient connection = new TcpClient();

        static void Main(string[] args)
        {
            try
            {
                connection.Connect("localhost", 5554);
                NetworkStream stream = connection.GetStream();

                ReadDataToConsole(stream);
                SendCommand(stream, "power status discharging");

                string command = string.Format("power capacity {0}", 50);
                SendCommand(stream, command);

                stream.Close();
                connection.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The following error has occured: {0}", ex.Message);
            }
        }

        private static void ReadDataToConsole(NetworkStream stream)
        {
            var responseBytes = new byte[connection.ReceiveBufferSize];
            stream.Read(responseBytes, 0, connection.ReceiveBufferSize);

            string responseText = Encoding.ASCII.GetString(responseBytes).Trim(new[] { ' ', '\0', '\n', '\r' });
            if (!string.IsNullOrEmpty(responseText))
                Console.WriteLine("Response: '{0}'.", responseText);
        }

        private static void SendCommand(NetworkStream stream, string command)
        {
            Console.WriteLine("Sending command '{0}'.", command);
            byte[] commandBytes = Encoding.ASCII.GetBytes(command + "\r");
            Buffer.BlockCopy(command.ToCharArray(), 0, commandBytes, 0, commandBytes.Length);

            stream.Write(commandBytes, 0, commandBytes.Length);

            ReadDataToConsole(stream);
        }

    }
}

这是程序的输出:

Response: 'Android Console: type 'help' for a list of commands'.
Sending command 'power status discharging'.
Response: 'OK'.
Sending command 'power capacity 50'.

我不确定是什么导致了问题。

我在这里先向您的帮助表示感谢!

4

2 回答 2

0

您介意发布您的工作代码吗?这是我使用的代码(供未来的访问者使用):

using (TcpClient client = new TcpClient(host, port))
{
    using (NetworkStream stream = client.GetStream())
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.AutoFlush = true;
                foreach (string command in commandList)
                {
                    writer.WriteLine(command);
                    string response = reader.ReadLine();
                    Thread.Sleep(5000);
                }
            }
        }
    }
}

马丁

于 2014-04-05T05:35:39.107 回答
0

如果有人想知道,我通过将NetworkStreamwith包装StreamReaderReadDataToConsole()函数和函数StreamWriter中来解决问题SendCommand()。确保AutoFlushtrueStreamWriter

现在一切正常!

于 2013-05-01T21:04:46.767 回答