【问题标题】:Sending and receiving an image file C#发送和接收图像文件 C#
【发布时间】:2011-07-25 04:23:51
【问题描述】:

我一直在努力通过套接字发送图像文件。我相信我非常接近,但我还没有得到它。我正在尝试将图像从服务器发送到客户端。

这是我的服务器代码:

//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;

我想我很接近,但我可能很遥远。我是网络新手,需要帮助。非常感谢。

【问题讨论】:

  • 您有任何问题,还是只是与我们分享这条信息? (半开玩笑的意思)

标签: c# .net sockets networking image


【解决方案1】:

问题在于,在您的客户端中,您假设您从服务器收到了 100000 个字节,并且您将所有 100000 个字节都放入了内存流中。

TcpClient 的 MSDN 页面上有一个很棒的示例,它显示了使用底层 NetworkStream 从 TcpClient 接收。此外,您还需要跟踪实际收到的字节数(这是NetworkStream.Read 函数的返回值)。最后,您需要继续阅读,直到没有更多数据可以从主机读取。如果您的图像大于缓冲区,那么您也只会有部分图像。 NetworkStream.Read 链接页面上的示例显示在有可用数据时不断从流中读取。

【讨论】:

  • 非常感谢,我相信我现在可以让它工作了:D。
  • 我明白了 :D :D :D :D :D。非常感谢。
  • 很高兴您能成功,感谢您接受我的回答!
猜你喜欢
  • 2012-08-10
  • 2012-01-02
  • 2019-08-03
  • 2014-09-30
  • 2021-07-10
  • 2010-10-19
  • 2015-01-08
  • 2017-10-24
  • 2016-05-02
相关资源
最近更新 更多