NetMQ订阅者使用已发布的消息进行阻止

时间:2015-10-26 18:09:51

标签: c# publish-subscribe netmq

我有一个Message Publishing Server类,它在构造时创建一个PUB套接字,代码如下:

this.context = NetMQContext.Create();
this.pubSocket = this.context.CreatePublisherSocket();
var portNumber = this.installerSettings.PublisherPort;
this.pubSocket.Bind("tcp://127.0.0.1:" + portNumber);

使用messagePublishingServer.Publish(message)发送消息:

this.pubSocket.SendMoreFrame(string.Empty).SendFrame(message);

以下xBehave测试...

    [Scenario]
    public void PublishMessageScenario()
    {
        MessagePublishingServer messagePublishingServer = null;
        NetMQContext context;
        NetMQ.Sockets.SubscriberSocket subSocket = null;
        string receivedMessage = null;

        "Given a running message publishing server"._(() =>
        {
            var installerSettingsManager = A.Fake<IInstallerSettingsManager>();
            var settings = new InstallerSettings { PublisherPort = "5348" };
            A.CallTo(() => installerSettingsManager.Settings).Returns(settings);
            messagePublishingServer = new MessagePublishingServer(installerSettingsManager);
        });

        "And a subscriber connected to the publishing server"._(() =>
        {
            context = NetMQContext.Create();
            subSocket = context.CreateSubscriberSocket();
            subSocket.Options.ReceiveHighWatermark = 1000;
            subSocket.Connect("tcp://127.0.0.1:5348");
            subSocket.Subscribe(string.Empty);
        });

        "When publishing a message"._(() =>
        {
            messagePublishingServer.Publish("test message");

            // Receive the topic
            subSocket.ReceiveFrameString();

            // and the message
            receivedMessage = subSocket.ReceiveFrameString();
        });

        "Then the subscriber must have received it"._(() =>
        {
            receivedMessage.Should().NotBeNullOrEmpty();
            receivedMessage.Should().Be("test message");
        });
    }

...在第一个subSocket.ReceiveFrameString()中阻止我发现意外。订阅者套接字是否已将已发布的消息排队,直到调用接收为止?

2 个答案:

答案 0 :(得分:1)

发布者就像广播一样,如果您在发布者发布时没有连接并订阅,则会错过该消息。我的建议是在用户连接后暂停100ms(仅用于测试)。

答案 1 :(得分:0)

从源头(ReceivingSocketExtensions.cs ):

    /// Receive a single frame from socket, blocking until one arrives, and decode as a string using ...
    public static string ReceiveFrameString([NotNull] this IReceivingSocket socket)

    /// If no message is immediately available, return <c>false</c>.
    public static bool TryReceiveFrameString([NotNull] this IReceivingSocket socket, out string frameString)