C# Socket Client - continuous receive

Stefano Mora 1 Reputation point
2021-09-24T09:46:55.877+00:00

Hi all,
I'm writing a program that includes a slightly modified version of the socket client based on https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

I added a thread:

    private void ThReceive(object objClient)  
    {  
        Socket client = (Socket)objClient;  

        Debug.WriteLine("[PlcSocket][ThReceive] thread");  
        while (true)  
        {  
            Debug.WriteLine("Receive v");  
            Receive(client);  
            Debug.WriteLine("Receive ^");  

            receiveDone.WaitOne();  

            Debug.WriteLine("[PlcSocket][ThReceive] received data!");  
        }  
    }  

At the beginning the client connects the server.
When I send a 4-bytes command, the data is sent, it is received by the server that echoes the packet.
The client receives the notifications in two times:

[PlcSocket] cmd1  
[PlcSocket][SendCallback] Sent 4 bytes to server.  
[ReceiveCallback] bytes 4  
[ReceiveCallback] bytes 0  

This is ok and the receiveDone exits inside the thread and continues the loop recalling the Receive() function to wait another reply from the server.
But now the ReceiveCallback is triggered again with a 0-bytes reply ... and so on.

...  
Receive v  
BeginReceive ..  
[ReceiveCallback] bytes 0  
Receive ^  

[PlcSocket][ThReceive] received data!  
 
Receive v  
BeginReceive ..  
[ReceiveCallback] bytes 0  
Receive ^  

[PlcSocket][ThReceive] received data!  

Receive v  
BeginReceive ..  
[ReceiveCallback] bytes 0  
Receive ^  

[PlcSocket][ThReceive] received data!  
Receive v  
...  

This generates an infinite loop!
How can I stop the loop in the receiving phase ?

Thanks!

Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2021-09-24T11:57:44.16+00:00

    Asynchronous socket logic should never contain a receive loop. A receive loop (polling) is found in synchronous logic.

    It sounds like you really want a client that is also a server.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.