I am struggling with the C# TCP Client BeginRead Method.
I am communicating with a machine as Server.
Since the machine sends push packets when a button is pressed, I need to listen all the time. I am doing that asynchronously via BeginRead(..).
To the first request sent to the machine (10 Bytes), the Response is correctly read (3 Bytes). If i repeat some other kind of request, the BeginRead just returns an Array of 00 Bytes (Lenght 1024).
The Wireshark Screenshots prove that this is a problem of my c# application.
The Push Messages from the machine aren't working after that second request too.
internal void StartRecieveContinuous()
{
Open();
int dataLenght = 1024;
this.LastRecievedData = new byte[dataLenght];
NetworkStream stream = Client?.GetStream() ?? throw new Exception("The TCP Client wasn't initialized!");
stream.BeginRead(LastRecievedData, 0, dataLenght, CallbackDataRecieved, stream);
ListenerRunning = true;
}
private void CallbackDataRecieved(IAsyncResult ar)
{
ListenerRunning = false;
// Debug
System.Diagnostics.Debug.WriteLine(string.Join(" ",this.LastRecievedData.Take(20).Select(x => x.ToString("X"))));
// Debug
if((this.LastRecievedData?.Count(x => x > 0) ?? 0) > 0)
{
EventDataRecieved?.Invoke(this, new DataRecievedArgs(this.LastRecievedData.Take(this.LastRecievedData?.Length ?? 0).ToArray()));
}
StartRecieveContinuous();
}
Debug Console Logs (hex):
5 1 80 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (First Response)
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (Second Response)
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (Button Press Event Data)
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (Button Release Event Data)
Edit:
I tried using endRead but my problem remains:
private void CallbackDataRecieved(IAsyncResult ar)
{
NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState;
myNetworkStream.EndRead(ar);
ListenerRunning = false;
System.Diagnostics.Debug.WriteLine(">>> " + string.Join(" ", this.LastRecievedData.Take(20).Select(x => x.ToString("X"))));
if((this.LastRecievedData?.Count(x => x > 0) ?? 0) > 0)
{
EventDataRecieved?.Invoke(this, new DataRecievedArgs(this.LastRecievedData.Take(this.LastRecievedData?.Length ?? 0).ToArray()));
}
StartRecieveContinuous();
}

