pebbe / zmq4

A Go interface to ZeroMQ version 4
BSD 2-Clause "Simplified" License
1.17k stars 166 forks source link

Question regarding graceful exit from poll #191

Open dandare100 opened 1 year ago

dandare100 commented 1 year ago

I would like to understand the best practice for gracefully exiting a poll loop when using this library (or zmq poll in general)

I have the following crude example, which works fine : Is there a more elegant way to do it ?

I realize there is only 1 socket in this example but more will be added.

Eish:
    for {

        sockets, _ := poller.Poll(time.Second * 3)

        for _, socket := range sockets {
            switch s := socket.Socket; s {
            case sub1:
                address, err := s.Recv(0)
                if err != nil {
                    log.Errorf("Error receiving zmq message(1) : %v", err)
                    continue
                }
                if msg, err := s.Recv(0); err != nil {
                    log.Errorf("Error receiving zmq message(2) : %v", err)
                    continue
                } else {
                    mess := string(msg)
                    fmt.Print("Received message from " + address + " channel.")
                    fmt.Printf("%+v\n", mess)
                }
            }

        }

        select {
        case <-ctx.Done():
            log.Infof("Exiting zmq.")
            break Eish
        case <-time.After(time.Millisecond * 1):
        }

    }