Didn't receive the full message in TCP server-client

59 Views Asked by At

When I get data on server app then it is half sometime and most of the time I get the full message I don't know how to fix this (because from client app, I add products in cart and in server app I show those products that are added in cart in client app so after 10-15 product added when I add a new product then I get half I tried to get it fixed because in this scenario when I get the half message I will not be able to see that product in server app, only able to see when I add 2-3 more products after that and that half message product will show in list too).

I tried to accumulate message but not working.

What is the issue in my code?

byte[] remainingData;
private StringBuilder receivedMessage = new StringBuilder();
protected override void OnReceived(byte[] buffer, long offset, long size)
{
    Task.Run(async () =>
    {
        try
        {
            var message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
            //var message = BinaryProtocol.DecodeMessage(buffer,ref remainingData);
            // Append the chunk to the accumulated message
            receivedMessage.Append(message);

            // Check if the accumulated message contains a complete message
            while (TryGetCompleteMessage(out string completeMessage))
            {
                await ProcessMessage(completeMessage);
                // Process the complete message
                messageQueue.Add(completeMessage);
                receivedMessage = new StringBuilder();
            }
            if (receivedMessage.Length > 0)
            {
                // Do something with incomplete message, e.g., log or process partially received data
                Debug.WriteLine("Incomplete message: " + receivedMessage.ToString());
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"Error processing received data: {ex.Message}");
            DependencyService.Get<ToastService>().ShowSnackBar($"Error processing received data: {ex.Message}");
        }
    });
}
private bool  TryGetCompleteMessage(out string completeMessage)
{
    completeMessage = null;

    // Check if the accumulated message contains a newline character
    int newlineIndex = receivedMessage.ToString().IndexOf('\n');
    if (newlineIndex >= 0)
    {
        int messageLength = newlineIndex + 1;
        // Extract the complete message up to the newline character
        completeMessage = receivedMessage.ToString(0, newlineIndex);

        // Remove the processed message from the accumulated data
        receivedMessage.Remove(0, messageLength);

        return true;
    }

    return false;
}
0

There are 0 best solutions below