pebbe / zmq4

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

PUB/SUB example doesn't work! #59

Closed paulm17 closed 9 years ago

paulm17 commented 9 years ago

Hi,

https://raw.githubusercontent.com/pebbe/zmq4/master/examples/psenvpub.go

I am unable to send messages without it being in a loop.

Only the messages in the loop get sent.

package main

import (
    zmq "github.com/pebbe/zmq4"
    "time"
)

func main() {
    //  Prepare our publisher
    publisher, _ := zmq.NewSocket(zmq.PUB)
    defer publisher.Close()
    publisher.Bind("tcp://10.101.45.3:5563")

    publisher.Send("B", zmq.SNDMORE)
        publisher.Send("WTF! 1 ", 0)

        publisher.Send("B", zmq.SNDMORE)
        publisher.Send("WTF! 2 ", 0)

        publisher.Send("B", zmq.SNDMORE)
        publisher.Send("WTF! 3 ", 0)

        publisher.Send("B", zmq.SNDMORE)
        publisher.Send("WTF! 4 ", 0)

        publisher.Send("B", zmq.SNDMORE)
        publisher.Send("WTF! 5 ", 0)

for {
        //  Write two messages, each with an envelope and content
        publisher.Send("A", zmq.SNDMORE)
        publisher.Send("We don't want to see this", 0)
        publisher.Send("B", zmq.SNDMORE)
        publisher.Send("We would like to see this", 0)
        time.Sleep(time.Second)
    }

    time.Sleep(time.Second)
}
pebbe commented 9 years ago

Put a sleep before the first send. Give your subscriber time to subscribe. A publisher doesn't wait for subscribers. If there is no subscriber, the mesage is lost.

Please post questions on how to use ZeroMQ to the mailing list. http://zeromq.org/docs:mailing-lists

paulm17 commented 9 years ago

I figured it out.

    func main() {
            //  Prepare our publisher
            publisher, _ := zmq.NewSocket(zmq.PUB)
            defer publisher.Close()
            publisher.Bind("tcp://10.101.45.3:5563")

            time.Sleep(time.Second * 5);

            publisher.Send("B", zmq.SNDMORE)
            publisher.Send("WTF! 1 ", 0)

            publisher.Send("B", zmq.SNDMORE)
            publisher.Send("WTF! 2 ", 0)

            time.Sleep(time.Second * 5);
    }

Seems it needs a wait before the first send and after the last send otherwise the send does not occur due to the socket closing!