// establish the net.UDPConn and context.Context here.

go func() {
    for {
        if err := conn.Read(p); err != nil {
            return
        }
        // do something with p
    }
}()

go func() {
    <-ctx.Done()
    conn.Close() // will interrupt the above goroutine with an error
    return
}()


On Tue, Mar 21, 2017 at 5:18 PM, Florian Forster <o...@verplant.org> wrote:
> Hi Go nuts,
>
> I have a (server) function that gets a context.Context and listens on a
> net.UDPConn. I would like this function to receive and handle network
> packets, but close the socket and return as soon as the context is
> cancelled.
>
> Ideally, I'd like to do something along these lines:
>
> for {
>   select {
>   case pkg := <- conn:
>     handle(ctx, pkg)
>   case <- ctx.Done():
>     // defer conn.Close() is called here
>     return ctx.Err()
>   }
> }
>
> I'm unable to find anything that would allow me to select on the connection,
> unfortunately. Is there a way to turn an UDP socket into a channel?
>
> The next best thing would likely be to read from the connection with a
> relatively short timeout and check ctx.Done() periodically. That sort of
> busy waiting is not as elegant as I had hoped though.
>
> Thanks for any pointers you might be able to share! :) Best regards,
> —octo
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to