我尝试了各种不同的事情,但这基本上是我想要做的。设置进程中的 pubsub。我重新运行了这段代码,但在尝试将 pub 套接字连接到转发器设备的前端时,连接被拒绝。
这是代码
string expectedAddress = "XXXX";
string message = "hello its me";
int count = 0;
using (var context = ZmqContext.Create())
{
using (var forwarderDevice = new ForwarderDevice(context, "inproc://front", "inproc://back", DeviceMode.Threaded))
{
using (var pub = Helper.GetConnectedPublishSocket(context, "inproc://front"))
{
using (var sub = Helper.GetConnectedSubscribeSocket(context, "inproc://back"))
{
forwarderDevice.Start();
Helper.SendOneSimpleMessage(expectedAddress, message, pub);
var zmqMessage = Helper.ReceiveMessage(sub);
Assert.AreEqual(count, zmqMessage.FrameCount);
Frame frame = zmqMessage[0];
var address = Encoding.Unicode.GetString(frame.Buffer);
Assert.AreEqual(expectedAddress, address);
}
}
forwarderDevice.Stop();
}
}
好的第一件事我知道我做错了......在您尝试连接到设备之前,应该直接在设备创建之后开始。第二件事是设备在另一个线程上启动,并且在主线程尝试连接时可能尚未准备好,因此您需要阻止一些方法,直到它准备好。代码现在看起来像:
string expectedAddress = "XXXX";
string message = "hello its me";
int count = 0;
using (var context = ZmqContext.Create())
{
using (var forwarderDevice = new ForwarderDevice(context, "inproc://front", "inproc://back", DeviceMode.Threaded))
{
forwarderDevice.Start();
while (!forwarderDevice.IsRunning)
{ }
using (var pub = Helper.GetConnectedPublishSocket(context, "inproc://front"))
{
using (var sub = Helper.GetConnectedSubscribeSocket(context, "inproc://back"))
{
Task<ZmqMessage> task = Task.Run(() =>
{
var zmqMessage = Helper.ReceiveMessage(sub);
return zmqMessage;
});
Helper.SendOneSimpleMessage(expectedAddress, message, pub);
task.Wait();
var result = task.Result;
Assert.AreEqual(count, result.FrameCount);
Frame frame = result[0];
var address = Encoding.Unicode.GetString(frame.Buffer);
Assert.AreEqual(expectedAddress, address);
}
}
forwarderDevice.Stop();
}
}
我没有收到任何错误,但我也从未收到消息