I want to use UDP sockets for my XNA-Networkgame. And now I'm trying to code a reliable Listenerthread, but there are some problems.
If I use socket.Receive, it will wait for the packet. This is normal for my Listenerthread. My thread has a while loop as follows:
while(Listen == true) { socket.Receive(...); }
But if I change the Listen-Flag to false (if I want to stop listening), it will get stuck in the last .Receive ().
Then I looked at .BeginReceive () Methods. It will call the method if the packet arrives. But to get the data, I have to use .EndReceive (), and this is what I came across. I want to still listen to packets and not stop listening if a packet arrives.
Therefore, I still use the blocking version with ".Receive ()". I could force the listening thread to cancel by calling: Thread.abort (), but that is not good.
I am currently testing whether data is available:
while(Listen == true) { if(socket.Available > 0) { socket.Receive(...); } }
But I think this is not the best way ... If, soon after the if-sentence, another thread calls socket.Receive (..), it will again be unintentional. There is no way to cancel the .Receive (..) method? I tried to set a timeout, but if .Receive timesout, it will throw an exception ...
I need a simple udp-listening thread, I can stop gracefully. :-) On MSDN I did not find an example of a listener that listens for several packets. How to deal with this other programmer?
multithreading udp xna sockets
user437899
source share