我正在尝试使用NetMQ(3.3.3.4)并创建pub-sub模式。
我希望主机/服务器在一个端口(9000)上侦听所有传入数据,并将数据转发到另一个端口(9001)上的所有客户端/订户。
客户端将在9000上发送数据并接收9001上发送的所有消息(由任意人发送)。
根据文档,我创建了类似下面的代码,但我无法使其工作。主要是,我相信,因为ReceiveReady
永远不会被召唤!
我认为它应该如何运作:
client.Publish
应该导致host.SubscriberSocket_ReceiveReady
中的第一行解除阻止并将数据传递到另一个套接字Task
中
结果:
// This line is never reached
上的断点永远不会到达PublisherSocket
构造函数,或者我在主机中使用_publisherSocket.Bind(address)
或在客户端使用_publisherSocket.Connect(address)
我做错了什么?
主机
public class MyNetMQHost {
private NetMQSocket _publishSocket;
private NetMQSocket _subscribeSocket;
private NetMQPoller _poller;
public MyNetMQHost(string publishAddress = "@tcp://localhost:9001", string subscribeAddress = "@tcp://localhost:9000") {
Task.Factory.StartNew(() => {
using (_publishSocket = new PublisherSocket(publishAddress))
using (_subscribeSocket = new SubscriberSocket(subscribeAddress))
using (_poller = new NetMQPoller { _publishSocket, _subscribeSocket }) {
_subscriberSocket.ReceiveReady += SubscriberSocket_ReceiveReady;
_poller.Run();
}
});
}
private void SubscriberSocket_ReceiveReady(object sender, NetMQSocketEventArgs e) {
var data = e.Socket.ReceiveMultipartBytes(); // This line is never reached
_publishSocket.SendMultipartBytes(data);
}
}
客户端
public class MyNetMQClient {
private readonly NetMQSocket _publishSocket;
private readonly NetMQSocket _subscribeSocket;
public MyNetMQClient(string publishAddress = ">tcp://localhost:9000", string subscribeAddress = ">tcp://localhost:9001") {
_publishSocket = new PublisherSocket(publishAddress);
_subscribeSocket = new SubscriberSocket(subscribeAddress);
Task.Factory.StartNew(() => {
while (true) {
byte[] frameBytes = _subscribeSocket.ReceiveFrameBytes();
int one = 1; // This line is never reached
}
});
}
public void Publish(byte[] data) {
_publishSocket.SendFrame(data);
}
}
测试
public class Tester {
public void MyTester() {
MyNetMQHost host = new MyNetMQHost();
MyNetMQClient client = new MyNetMQClient();
client.Publish(Encoding.Unicode.GetBytes("Hello world!");
}
}
答案 0 :(得分:3)
您的经纪人和客户都不会打电话给他们。 在经纪人呼叫suscriber.Subscribe("")订阅所有。在您的客户端订阅您想要的任何内容。
在你的经纪人中,你应该使用XSubscriber和XPublisher来移动susvriptions。这样你就不需要全部订阅了。您可以使用Proxy类。