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.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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!
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.