我正在尝试使用 NetMQ (3.3.3.4) 并创建一个 pub-sub 模式。
我希望主机/服务器监听一个端口(9000)上的所有传入数据,并将数据转发给另一个端口(9001)上的所有客户端/订阅者。
然后,客户端将在 9000 上发送数据,并在 9001 上接收(由任何人)发送的所有消息。
按照文档,我创建了类似下面的代码,但我无法让它工作。主要是,我相信,因为ReceiveReady
从不调用!
我认为它应该如何工作:
client.Publish
应该导致第一行host.SubscriberSocket_ReceiveReady
解除阻塞并将数据传递到另一个套接字- 当数据被传递时,它应该出现在
Task
客户端的无限运行中
结果:
// This line is never reached
永远无法达到断点- 任何地方都没有例外。
- 切换主机上的端口,使 publish = 9000 和 subscribe = 9001 无效
- Windows 防火墙已关闭,因此不应有任何阻塞
- 如果我将地址放入
PublisherSocket
构造函数中,或者我_publisherSocket.Bind(address)
在 Host 或_publisherSocket.Connect(address)
Client 中使用,这没有区别
我究竟做错了什么?
主持人
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!");
}
}