我正在尝试使用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'.
我不确定是什么导致了问题。
我在这里先向您的帮助表示感谢!