简体   繁体   中英

Compress the data sent via a C# socket?

I'm trying C# sockets to send images. It works, but it's unstable. The images sent through are quite large and are updated very quickly which causes it to flicker every now and then. I'm looking for a way to compress the data sent if possible. I'm using this code:

Server side:

System.IO.MemoryStream stream = new System.IO.MemoryStream();

// !! Code here that captures the screen !!

bitmap.Save(stream, myImageCodecInfo, myEncoderParameters);

byte[] imageBytes = stream.ToArray();
stream.Dispose();

// Send the image
clientSocket.Send(imageBytes);

// Empty the byte array?
for (int i = 0; i < imageBytes.Length; i++)
{
    imageBytes[i] = 0;
}

Client side:

private void OnConnect(IAsyncResult ar)
{
    try
    {
        MessageBox.Show("Connected");

        //Start listening to the data asynchronously
        clientSocket.BeginReceive(byteData,
                                    0,
                                    byteData.Length,
                                    SocketFlags.None,
                                    new AsyncCallback(OnReceive),
                                    null);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Stream Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void OnReceive(IAsyncResult ar)
{
    try
    {
        int byteCount = clientSocket.EndReceive(ar);

        // Display the image on the pictureBox
        MemoryStream ms = new MemoryStream(byteData);
        pictureBox1.Image = Image.FromStream(ms);
        }
    catch (ArgumentException e)
    {
        //MessageBox.Show(e.Message);
    }
    clientSocket.BeginReceive(byteData,0,byteData.Length,SocketFlags.None,new AsyncCallback(OnReceive),null);
}

I ended up using gzip.

Turns out the flicker wasn't due to it being updated very quickly, but was because of the way I had sockets set up. It wasn't sending the whole image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM