C #: UDP listener stream

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?

+7
multithreading udp xna sockets
source share
2 answers

Mark the Listen flag as changed so that changes are displayed between threads.

 public volatile bool Listen{get; set;} 

Handle the appropriate exceptions in your thread:

 Thread listener = new Thread(()=> { while(Listen == true) { try { socket.Receive(); } catch(ThreadInterruptException) { break; // exit the while loop } catch(SocketException) { break; // exit the while loop } } }); listener.IsBackground = true; listener.Start(); 

In the code where you switch the Listen flag to false , you either close the socket or interrupt the stream:

 Listen = false; socket.Shutdown(SocketShutdown.Both); socket.Close(); // // OR // listener.Interrupt(); 
+9
source share

Thanks Lyric and Matt Davis. It works fine, but is it ok to use Exceptions? I found out that only exceptions should be thrown if something bad / unexpected happens. (to stop blocking labels implied :-))

I handled an exception like this. I searched for the error code and interrupted the loop.

  try { broadcastSocket.ReceiveFrom(returnData, ref ep); //... } catch (SocketException ex) { if (ex.ErrorCode == 10004) { break; } } 

Why should i use

 socket.Shutdown(SocketShutdown.Both); 

before

 socket.Close(); 

Will closing () not disconnect the socket?

And if I want to use the socket again, is there a "restart" method, or should I create a new socket?

Hello user437899

+1
source share

All Articles