tags:

views:

618

answers:

2

I have a udp client that is listening for multicast messages. When it gets a message the message is parsed and the client resumes listening. If the application is shutdown while the socket.ReceiveFrom method is blocking, how can I interrupt this process and continue?

I have the socket running on a different thread and I've tried to issue an interrupt to that thread and then join, but the interrupt doesn't work the socket.ReceiveFrom never returns unless it gets a message.

I have also tried setting a timeout on the socket, but this isn't ideal since it generates an exception on timeout and since I'm always listening I will be generating a ton of timeouts, catching them and then go back to listening.

Any ideas what i can try here?

+1  A: 

Found I can make the socket available outside the thread being blocked and can call a socket.Close. This interrupts and throws a SocketException. Still seems a bit dirty but it gets the job done.

Anyone have a better way?

Kelly
Implement the thread as a class that has the socket as a private member. Add a public `Shutdown` method that does the Socket.Close. Call it from outside, when you decide you want to give up. It's called Encapsulation.
John Saunders
That is what I've done. It just doesn't seem clean to be calling the close on the socket from a different thread like that. But it works.
Kelly
A: 

I am not socket expert, but can still try.

Use combination of following two things to make a non-blocking socket.

1) Use select function with timeout to wait on a particular socket. After timeout check if you still want to wait on that socket or not.

2) Make you recvfrom call non-blocking by using O_NONBLOCK. http://www.kegel.com/dkftpbench/nonblocking.html

Use the above link to study about how to make recvfrom non-blocking.

Google for select.