[英]Networkstream not responding
我正在嘗試通過網絡流發送圖像,這是我的客戶端代碼:
private void Form1_Load(object sender, EventArgs e)
{
TcpClient client=new TcpClient();
client.Connect("127.0.0.1", 10);
NetworkStream ns = client.GetStream();
Bitmap screen = GetDesktopImage();//generate a screenshot.
MemoryStream ms = new MemoryStream();
screen.Save(ms, ImageFormat.Png);
byte[] byteCount = BitConverter.GetBytes((int)ms.Length);
ms.Position = 0;
ns.Write(byteCount, 0, byteCount.Length);
ms.CopyTo(ns);
ms.SetLength(0);
}
這是服務器:
private void Start()
{
TcpListener listen = new TcpListener(IPAddress.Any, 10);
listen.Start();
NetworkStream ns = new NetworkStream(listen.AcceptTcpClient().Client);
byte[] temp = new byte[4];
ns.Read(temp, 0, 4);
int count = BitConverter.ToInt32(temp, 0);
byte[] buff = new byte[count];
pictureBox1.Image = Image.FromStream(ns);
}
private void Form1_Load(object sender, EventArgs e)
{
Thread th = new Thread(Start);
th.Start();
}
我在圖片框上看不到任何內容,我猜程序在這里掛起了pictureBox1.Image = Image.FromStream(ns);
剛剛在此處添加了一個斷點,但它不起作用。 **只有當我關閉客戶端程序並停止調試時,我才能在服務器端的圖片框上看到圖像。 為什么會這樣?有什么想法嗎?
我的猜測是Image.FromStream
在繪制完整圖像時不知道要停止讀取。 也許PNG格式甚至不允許這樣做。 您需要為Image.FromStream
提供大小有限的流。 最簡單的方法是使用BinaryReader.ReadBytes(count)
讀取所需的確切字節數。
ns.Read(temp, 0, 4);
:這是一個錯誤,因為它假定讀取將恰好返回4個字節。 情況可能並非如此。 再次使用BinaryReader.ReadInt32
安全地讀取一個int。
更好的是,放棄自定義序列化格式,並使用諸如protobuf length前綴的名稱。 或者,HTTP或WCF。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.