[英]C# Xamarin Recieve and Display image from Stream Byte Array with TCP Sockets
I am currently working on a project that I send an Image through TCP using sockets from a WinForm Application to a Xamarin Android App in the same network .
我已經使用客戶端(也是 Winforms)測試了服務器( WinForms )代碼並管理它工作。 但是問題來了,當我在 Xamarin 中為 Android 客戶端編碼時,我發現我不能以同樣的方式使用 Bitmap,所以我試圖尋找其他方式。
問題在於 android 客戶端代碼。 我在調試中檢查了圖像字節從服務器 - >客戶端全部通過。
在 Android 客戶端上:如果我刪除while loop
並開始使用發送按鈕(服務器)和連接按鈕(客戶端)播放一些圖像在客戶端顯示。 這很奇怪
我不是這些問題的專家,因此請隨時提出任何更正建議
我使用的代碼
我的WinForms 服務器中的代碼是這樣的。
private void StartServer_Click(object sender, EventArgs e)
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 9999);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(iep);
server.Listen(100);
Console.WriteLine("Waiting for client....");
client = server.Accept();
}
private void SendImage_Click(object sender, EventArgs e)
{
Bitmap bmp = TakingScreenshotEx1(); // method for taking screenshot
bmp.Save("1.jpeg", ImageFormat.Jpeg); // the name of the screenshot taken, just before
byte[] buffer = ReadImageFile("1.jpeg"); // read the saved image file
int v = client.Send(buffer, buffer.Length, SocketFlags.None); // send the image
Console.WriteLine("Image SENT!");
}
我的WinForms 客戶端(新手但工作方法)
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 9999);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] buffer = new byte[1000000];
private async void Connect_Click(object sender, EventArgs e)
{
if(client.Connected != true)
client.Connect(iep);
await Task.Run(() => DoSomethingLong());
}
private async void DoSomethingLong()
{
while (true)
{
int v = client.Receive(buffer, buffer.Length, SocketFlags.None);
Console.WriteLine("Data Received!");
Stream stream = new MemoryStream(buffer);
var img = Bitmap.FromStream(stream);
pictureBox1.Image = img;
}
}
有問題的Android 客戶端
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 9999);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] buffer = new byte[1000000];
private async void Connect_Clicked(object sender, EventArgs e)
{
if (client.Connected != true)
client.Connect(iep);
await Task.Run(() => DoSomethingLong());
}
public Xamarin.Forms.ImageSource PhotoStream { get; set; }
private async void DoSomethingLong()
{
while(true){
int v = client.Receive(buffer, buffer.Length, SocketFlags.None);
Console.WriteLine("Data Received!");
Stream stream = new MemoryStream(buffer);
if (stream != null)
imgXam.Source = ImageSource.FromStream(() => stream);
}
}
解決了
遵循@Jason
的建議並將Invoke Method
放入Timer
中。 我能夠解決問題
Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
{
// called every 1 second
MainThread.BeginInvokeOnMainThread(() =>
{
});
return true; // return true to repeat counting, false to stop timer
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.