question

StefanoMora-9845 avatar image
0 Votes"
StefanoMora-9845 asked AgaveJoe answered

C# Socket Client - continuous receive

Hi all,
I'm writing a program that includes a slightly modified version of the socket client based on https://docs.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!

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AgaveJoe avatar image
1 Vote"
AgaveJoe answered

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes, you are right.
I opened the loop and corrected all the sequence of callbaks.
Thread is useless ...

Thanks!

0 Votes 0 ·