我已经制作了这些代码来使用 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 = IPAdress.HostToNetworkOrder(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;
}
}
删除 IPAdress.HostToNetworkOrder 到以下内容后编辑
int size = BitConverter.ToInt32(data,0);
还是有问题。问题是当我发送大小时,它以 5kb 的形式发送,但当我收到它时,我发现它更接近 2GB。
此外,我在这一行得到一个错误
read += stream.Read(data, read, data.Length - read);
带有以下消息
无法从传输连接读取数据。由于系统缺少足够的缓冲区空间或队列已满,因此可能会在套接字上执行操作。