我已经使这些代码发送和接收带有TCP套接字的图像,但接收代码不起作用。
这是发送代码:
public void SendImage()
{
int ScreenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int ScreenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(ScreenWidth, ScreenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(ScreenWidth, ScreenHeight));
bmpScreenShot.Save(Application.StartupPath + "/ScreenShot.jpg", ImageFormat.Jpeg);
byte[] image = new byte[1];
bmpScreenShot = ResizeBitmap(bmpScreenShot, 300, 300);
image = ImageToByte(bmpScreenShot);
//get the length of image (length of bytes)
int NumberOfBytes = image.Length;
//put the size into a byte array
byte[] numberofbytesArray = BitConverter.GetBytes(NumberOfBytes);
//send the size to the Client
int sizesend = sck.Send(numberofbytesArray, 0, numberofbytesArray.Length, 0);
if (sizesend > 0)
{
MessageBox.Show("Size Sent");
}
//send the image to the Client
int imagesend =sck.Send(image, 0, NumberOfBytes, 0);
if (imagesend > 0)
{
MessageBox.Show("Image Sent");
}
}
这是接收代码:
public void ReceiveImage()
{
if (sck.Connected)
{
{
NetworkStream stream = new NetworkStream(sck);
byte[] data = new byte[4];
//Read The Size
stream.Read(data, 0, data.Length);
int size = (BitConverter.ToInt32(data,0));
// prepare buffer
data = new byte[size];
//Load Image
int read = 0;
while (read != data.Length)
{
read += stream.Read(data, read, data.Length - read);
}
//stream.Read(data, 0, data.Length);
//Convert Image Data To Image
MemoryStream imagestream = new MemoryStream(data);
Bitmap bmp = new Bitmap(imagestream);
pictureBox1.Image = bmp;
}
}
}
问题是当我发送大小时,它发送为5kb但是当我收到它时我发现它是2GB并且出现此错误:
无法从传输连接中读取数据。可以执行套接字上的操作,因为系统缺少足够的缓冲区空间或者队列已满。
错误发生在此声明read += stream.Read(data, read, data.Length - read);
答案 0 :(得分:0)
我会尝试获取更小的数据块。在您的代码中,您开始使用所有数据(在失败的情况下一次2GB。将其降低到更小的数据 - 无论如何数据都以块的形式发送。例如:< / p>
read += stream.Read(buffer, read, 20480);
这将一次读取大约2k,以便不大于缓冲区空间或对队列来说太大。
如果您已经分配了2GB的缓冲区,那么您的应用程序可能只剩下很少的内存。底层框架可能无法为自己分配2GB数据(总共分配4GB)来传输数据。