发送和接收图像文件C# [英] Sending and receiving an image file C#

查看:43
本文介绍了发送和接收图像文件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力通过套接字发送图像文件.我相信我已经很接近了,但是还没有得到.我正在尝试将图像从服务器发送到客户端.

I have been struggling for a while now to send an image file over sockets. I believe I am very close, but I haven't gotten it yet. I am trying to send the image from the server to the client.

这是我的服务器代码:

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

我认为我已经很近了,但我可能还很遥远.我是网络新手,请寻求帮助.非常感谢.

I think I am very close, but I might be far off. I am new to networking, and require help please. Thanks A lot.

推荐答案

问题是,在客户端中,您假设您从服务器收到了100000字节,并将所有100000字节放入内存流中.

The problem is that in your client, you are assuming that you received 100000 bytes from the server, and you're putting all 100000 bytes into the memory stream.

在MSDN页面上有一个很好的示例,用于TcpClient ,其中显示了使用基础NetworkStream从TcpClient接收消息.另外,您将需要跟踪实际收到的字节数(这是 NetworkStream.Read 函数).最后,您将要继续读取直到没有更多数据要从主机读取.如果您的图像大于缓冲区,那么您还将只有部分图像.链接页面上的 NetworkStream.Read 表示在有可用数据时不断从流中读取数据.

There is a great sample on the MSDN page for TcpClient which shows receiving from a TcpClient by using the underlying NetworkStream. Also, you will want to keep track of how many bytes you actually received (this is the return value from the NetworkStream.Read function). Finally, you'll want to keep reading until there is no more data to be read from the host. If your image is larger than your buffer, then you'll only have a partial image also. The sample on the linked page for NetworkStream.Read shows continually reading from the stream while there is data available.

这篇关于发送和接收图像文件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆