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

たとえば、Javaサーバー/クライアントに準拠する必要があるサーバーを作成する場合を除いて、HostToNetworkの順序を使用しないでください。その場合は、送信するintデータバッファの順序も変更する必要があります。

また、データを割り当ててそこにバイトを書き込む代わりに、クライアントで受信したバイトをメモリストリームに直接書き込むことでメリットが得られる場合があります。imagestream.Position = 0また、重要な点として、ビットマップコンストラクターに渡す前に設定することを忘れないでください。

于 2012-07-31T00:08:50.007 に答える