使用已发布消息阻塞NetMQ订阅者
本文关键字:NetMQ 消息 布消息 | 更新日期: 2023-09-27 18:19:15
我有一个消息发布服务器类,它在构造时创建一个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 test…
[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()
中的块,这是我意想不到的。订阅者套接字不应该将发布的消息排队,直到调用接收?
发布者就像收音机,如果您在发布者发布时没有连接和订阅,您就会错过消息。我的建议是在用户连接后设置100毫秒的睡眠时间(仅用于测试)。
从源(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)