2011-07-25 132 views
0

我一直在努力一段时间来发送图像文件在套接字上。我相信我非常接近,但我还没有得到它。我正尝试将图像从服务器发送到客户端。发送和接收图像文件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; 

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

+0

您有任何问题,或者您只是与我们分享这条信息? (意思是一个半笑话) – Tipx

回答

2

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

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

+0

非常感谢,我相信我现在能够得到它的工作:D。 – Killer1390

+0

我明白了:D:D:D:D:D。非常感谢。 – Killer1390

+0

我很高兴你的工作,并感谢您接受我的答案! – scwagner