簡體   English   中英

發送和接收圖像文件C#

[英]Sending and receiving an image file C#

我現在一直在努力通過套接字發送圖像文件。 我相信我非常接近,但我還沒有得到它。 我試圖將圖像從服務器發送到客戶端。

這是我的服務器代碼:

//Init listener
listener = new TcpListener(new IPEndPoint(IPAddress.Any, 550));

//Start listening for connections
listener.Start();
Console.WriteLine("Waiting for connection");
s = listener.AcceptSocket();
//If we reach here, we have a connection
Console.WriteLine("Connected");
//Get the screenshot and apply it to our memory stream
img = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
imgG = Graphics.FromImage(img);
imgG.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
img.Save("sc.jpg", ImageFormat.Jpeg);
//Convert image to byte array, and then send it
byte[] byteArray = ms.ToArray();
s.Send(byteArray);
s.Close();
Console.Read();

這是我的客戶端代碼:

client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse(IPBox.Text), 550));
s = client.Client;
buffer = new byte[100000];
s.Receive(buffer);
ms.Read(buffer, 0, 100000);
img = (Bitmap)Image.FromStream(ms);
imgContainer.Image = (Image)img;

我想我很親密,但我可能還很遙遠。 我是網絡新手,請求幫助。 非常感謝。

問題是在您的客戶端中,您假設您從服務器收到了100000個字節,並且您將所有100000個字節放入內存流中。

TcpClient的MSDN頁面上有一個很好的示例,它顯示了使用底層NetworkStream從TcpClient接收。 此外,您還需要跟蹤實際接收的字節數(這是NetworkStream.Read函數的返回值)。 最后,您將繼續閱讀,直到無法從主機讀取更多數據。 如果您的圖像大於緩沖區,那么您也只會有部分圖像。 NetworkStream.Read鏈接頁面上的示例顯示在有可用數據的情況下從流中連續讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM