none
Async Socket Receive Exact amount of data Example? RRS feed

  • Question

  • Hi

    Im having a bit of a problem working out how to receive an exact amount of

    data. the reason i want to receive the exact amount of data is that i have a header that i recieve from a server this header has the size of the data then from the size received i can work out the exact amount of data i want to use.

    so the question is how can i specify the amount of data that i want to receive?

    I have tried the below example but the onrecieve callback would recieve incremented amounts of data.


    // use OnRecieve callback
    psSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), this.m_psSocket);
    
    // callback
    private void OnReceive(IAsyncResult ar)
    {
    Socket clientSocket = (Socket)ar.AsyncState;
    
                int bytesRead = clientSocket.EndReceive(ar);
    
                if (bytesRead > 0)
                {
    
                }
    
    }

    Thanks




    • Edited by Nz tribute Sunday, March 10, 2013 4:51 AM
    • Moved by Lisa Zhu Monday, March 11, 2013 6:17 AM networking and communication
    Sunday, March 10, 2013 12:36 AM

All replies

  • also is there a function similar to beginreceivemessagefrom for TCP async socket
    Sunday, March 10, 2013 4:54 AM
  • Hi Nz,

    From your description, I ‘d like to move this post to  the most related forum.

    There are more  experts in this aspect, so you will get  better support and  may have more luck getting answers.

    Thanks for your understanding.

    Regards,


    Lisa Zhu [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, March 11, 2013 6:17 AM
  • Hi,

    You can use global variable to record total data and when the total variable is same as header.size then you can discard rest of data. 

    totalBytes += bytesRead;

     

    Regards,
    Christian HL
    Microsoft Online Community Support


    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

    • Proposed as answer by ChrisHL Monday, March 18, 2013 2:50 AM
    • Unproposed as answer by ChrisHL Monday, March 18, 2013 2:50 AM
    • Proposed as answer by Christian HL - MSFT Monday, March 18, 2013 2:51 AM
    Tuesday, March 12, 2013 2:30 AM