Olivarsham
Olivarsham

Reputation: 1731

Continuously receive data from socket and reading selected data

I want to read a weighing machine socket and update its value in GUI.

The socket will send the current weight value continuosly. My data (weight) will be less than 100 bytes.

If i give buffer as 100, its taking too much time to update the current value as it has to read all the remaining bytes. So, I changed buffer size to 4096 bytes. Now the value is updating Real Time.

My question is,
--- Is giving 4096 bytes is really a great overhead in performance (when compared to 100 bytes)??
--- Is it possible to read clear all the available data and just read last 100 bytes when ever a message is received??

The code I am using for Call Back:

   private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                //Get received bytes count
                var bytesRead = _clientSocket.EndReceive(ar);
                if (bytesRead > 0)
                {
                    //Copy received bytes to a new byte array
                    var receivedBytes = new byte[ReceiveBufferSize];

                    Array.Copy(_buffer, 0, receivedBytes, 0, 100); //100 byte is enough for checking the data

                    FormatAndUpdateGUI(receivedBytes);

                }
                else
                {
                    throw new Exception("Error in Reading");
                }
        //Read more bytes 
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
            }
            catch (Exception ex)
            {
               throw new Exception("Error in Reading");
            }
        }

Upvotes: 0

Views: 1111

Answers (1)

Oren
Oren

Reputation: 3248

You should always be reading in bytesRead, so that you read the maximum available data at any given time. In this case you can also optimize your memory usage by using a byte array of size bytesRead so that it exactly matches what you need and not some predefined maximum.

Upvotes: 1

Related Questions