C#通过套接字发送图像
我试图通过连接到服务器的套接字发送屏幕截图,但我得到了一个异常(在服务器窗口上):参数无效,下面是代码: 客户端:C#通过套接字发送图像,c#,image,sockets,C#,Image,Sockets,我试图通过连接到服务器的套接字发送屏幕截图,但我得到了一个异常(在服务器窗口上):参数无效,下面是代码: 客户端: public static Image CaptureDesktop() { Rectangle bounds = default(Rectangle); System.Drawing.Bitmap screenshot = null; Graphics graph = default(Graphics); b
public static Image CaptureDesktop()
{
Rectangle bounds = default(Rectangle);
System.Drawing.Bitmap screenshot = null;
Graphics graph = default(Graphics);
bounds = Screen.PrimaryScreen.Bounds;
screenshot = new Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
graph = Graphics.FromImage(screenshot);
graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
return screenshot;
}
public static void PrepareImage()
{
Bitmap bmp = new Bitmap(CaptureDesktop());
Image f = (Image)bmp;
MemoryStream ms = new MemoryStream();
f.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
_clientSocket.Send(ms.ToArray());
Console.WriteLine("data sent");
}
服务器端:
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
private void ReceiveCallback(IAsyncResult AR)
{
Socket current = (Socket)AR.AsyncState;
int received = 0;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
_clientSockets.Remove(current);
return;
}
byte[] recBuf = new byte[received];
Array.Copy(_buffer, recBuf, received);
try
{
pictureBox1.Image = byteArrayToImage(recBuf);
}
catch (Exception a)
{
MessageBox.Show(a.Message);
}
}
例外情况是在这一行:Image returnImage=Image.FromStream(ms)
我的代码有什么问题?
谢谢:)服务器上接收到的数据可能是部分图像,您需要为部分接收到的数据添加前缀和缓冲区等。请检查。正是Sriram Sakthivel,它显示了标题栏的一小部分,以及许多包含异常的消息框,但是我不明白你发送的链接上有什么内容:/你必须存储收到的字节,直到你收到完整的数据。这个链接将指导你去做。我的理解是:我将每个接收到的字节存储在PacketProtocole中,当所有字节都被接收时,图像就完整了,对吗?不完全正确。您将数据存储到缓冲区中,并通过使用前缀(具有图像的长度)检查接收长度来等待完全接收。清楚了吗?