开发者

Sending and receiving an image file C#

开发者 https://www.devze.com 2023-03-22 10:43 出处:网络
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.

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.

Here is my server code:

//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, Scree开发者_运维百科n.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();

Here is my client code:

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.


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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消