![](/img/trans.png)
[英]C# Xamarin Recieve and Display image from Stream Byte Array with TCP Sockets
[英]c# Send/Recieve Image from Stream
我目前已經編寫了以下代碼。 客戶端和服務器端。 我想按需將圖像從服務器發送到客戶端。 該圖像將是來自服務器的屏幕截圖,因此我將始終使用不同的大小。
發送第一張圖像是一項完成得很好的任務。 但是當我發送下一個圖片框時不會刷新。 從調試中我可以看到從服務器到客戶端的字節成功通過。 但是代碼似乎只接收字節而不繼續使用代碼的 rest
“while”循環( client )的“commented”行似乎在調試中工作,但我看不到結果,因為程序卡在 while 循環中,我無法在前台獲取應用程序的window
我目前正在 windows 中進行測試,但客戶端將進行調整以在 android 上工作
服務器
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket client;
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = TakingScreenshotEx1();
bmp.Save("1.jpeg", ImageFormat.Jpeg);
byte[] buffer = ReadImageFile("1.jpeg");
int v = client.Send(buffer, buffer.Length, SocketFlags.None);
Console.WriteLine("Image SENT!");
}
private Bitmap TakingScreenshotEx1()
{
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var g = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
return bmpScreenshot;
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 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 static byte[] ReadImageFile(String img)
{
FileInfo fileinfo = new FileInfo(img);
byte[] buf = new byte[fileinfo.Length];
FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read);
fs.Read(buf, 0, buf.Length);
fs.Close();
GC.ReRegisterForFinalize(fileinfo);
GC.ReRegisterForFinalize(fs);
return buf;
}
}
客戶
public Form1()
{
InitializeComponent();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] buffer = new byte[1000000];
private void button1_Click(object sender, EventArgs e)
{
if(client.Connected != true)
client.Connect(iep);
// 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;
// }
}
正如Peter Duniho
指出的那樣, while loop
阻塞了 UI 線程
我在這里找到了一個合適的解決方案如何等待線程完成而不阻塞 UI
您還可以檢查 Invoking the Main Thread inside Timer Method
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.