我做我的第一个Xamarin跨平台应用程序。
我正在尝试显示一张图片,该图片来自我编写的TCP服务器。
起初,我尝试在每次请求站点时重新加载图片。但是由于同步读取流,因此该站点需要较长的时间来加载,并且还阻塞了UI。因此,我尝试异步读取网络流。但是,所以我没有显示图片。另外,我不确定所显示的数据是否完整。
public static async Task<bool> ReceivePicture(string sTCP, int iPort, Byte[] bData)
{
TcpClient client = new TcpClient // Creates a TCP Client
{
ReceiveTimeout = 800,
SendTimeout = 800
};
client = new TcpClient(sTCP, iPort); //Trys to Connect
await client.ConnectAsync(sTCP, iPort);
if (!client.Connected)
return false;
NetworkStream serverStream = client.GetStream();
string sSend = "DATA_PICTURE";
byte[] outStream = Encoding.UTF8.GetBytes(sSend);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[32];
int j = 0;
var ack = await serverStream.ReadAsync(inStream, j, inStream.Length);
UTF8Encoding encoder = new UTF8Encoding();
string sMessage = encoder.GetString(inStream, 0, ack);
string[] words = sMessage.Split(';');
Int32.TryParse(words[1], out int iPicSize);
sSend = "OK";
outStream = Encoding.UTF8.GetBytes(sSend);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
var encoding = Encoding.UTF8;
var i = 0;
byte[] inStreamPic = new byte[iPicSize];
var sb = new StringBuilder();
//while (!serverStream.DataAvailable)
//{
//}
//while (serverStream.DataAvailable)
//{
// serverStream.Read(inStreamPic, j, 1);
// j++;
//}
while ((i = await serverStream.ReadAsync(inStreamPic, 0, inStreamPic.Length)) != 0)
{
sb.Append(encoding.GetString(inStreamPic, 0, i));
if (!serverStream.DataAvailable) break;
}
img.Source = ImageSource.FromStream(() => new MemoryStream(inStreamPic));
bData = inStreamPic;
//var sFileName = Path.Combine(App.FolderPath, "Screen.png");
//File.WriteAllBytes(sFileName, bData);
//ImageConverter ic = new ImageConverter();
//File.WriteAllBytes(sFileName, bData);
//sFileName = img. ;
client.GetStream().Close();
client.Close();
return true;
}