0

我已经制作了这些代码来使用 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);

带有以下消息

无法从传输连接读取数据。由于系统缺少足够的缓冲区空间或队列已满,因此可能会在套接字上执行操作。

4

1 回答 1

1

不要使用 HostToNetwork 顺序,除非您正在创建一个应该与 java 服务器/客户端兼容的服务器。如果这样做,您还需要更改要发送的 int 数据缓冲区的顺序。

您还可以受益于将您在客户端收到的字节直接写入内存流,而不是分配数据并将字节写入内存流。imagestream.Position = 0还有一个重要的注意事项,在将其交给位图构造函数之前不要忘记设置。

于 2012-07-31T00:08:50.007 回答