使用.NETC连接到Android仿真器#
我正在尝试使用使用.NETC连接到Android仿真器#,android,.net,android-emulator,avd,networkstream,Android,.net,Android Emulator,Avd,Networkstream,我正在尝试使用TcpClient连接到Android仿真器。模拟器是Android 4.2.2,运行在localhost:5554上,我从AVD管理器开始。我能够连接并发送“电源状态释放”命令,但在发送第二个命令后,程序将挂起等待响应。当我使用Putty原始连接进行连接时,这些命令会起作用 以下是完整的代码: using System; using System.Net.Sockets; using System.Text; namespace AndroidBatteryChangeEmul
TcpClient
连接到Android仿真器。模拟器是Android 4.2.2,运行在localhost:5554上,我从AVD管理器开始。我能够连接并发送“电源状态释放”命令,但在发送第二个命令后,程序将挂起等待响应。当我使用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'.
我不确定是什么导致了这个问题
提前谢谢你的帮助 如果有人想知道,我通过在
ReadDataToConsole()
函数中使用StreamReader
包装NetworkStream
和SendCommand()
函数中使用StreamWriter
解决了这个问题。
确保StreamWriter
中的AutoFlush
为true
现在一切都好了 您介意发布您的工作代码吗?以下是我使用的代码(供将来的访问者使用): 马丁
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);
}
}
}
}
}