我正在尝试使用TcpClient
连接到Android模拟器。模拟器是运行在localhost:5554上的Android 4.2.2,我从AVD Manager开始。我能够连接并发送'power status discharge'命令,但在发送第二个命令后,程序挂起等待响应。当我使用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'.
我不确定导致问题的原因。
提前感谢您的帮助!
答案 0 :(得分:0)
如果有人想知道,我通过在NetworkStream
函数StreamReader
和ReadDataToConsole()
函数中StreamWriter
包裹SendCommand()
来解决问题。
确保AutoFlush
中的true
为StreamWriter
!
现在一切正常!
答案 1 :(得分: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);
}
}
}
}
}
马丁