我学会了如何在localhost
上使用ZeroMQ
,但我未能在远程IP上使用
Q1:
我需要经纪人吗?
如果是这样,Q2:
哪个经纪人以及如何做。?
更新:
还行。我使用的是ZMQ
天气更新示例,但使用远程 IP(不是localhost
)。这是我使用 C# ZMQ
绑定所做的(但是,我可以使用任何其他语言):
ZMQ 服务器:
using (var context = new ZContext())
using (var publisher = new ZSocket(context, ZSocketType.PUB))
{
string address = "tcp://*:5001";
publisher.Bind(address);
publisher.Send("msg")
}
代理:
using (var context = new ZContext())
using (var frontend = new ZSocket(context, ZSocketType.XSUB))
using (var backend = new ZSocket(context, ZSocketType.XPUB))
{
// Frontend is where the weather server sits
string localhost = "tcp://127.0.0.1:5001";
Console.WriteLine("I: Connecting to {0}", localhost);
frontend.Connect(localhost);
// Backend is our public endpoint for subscribers
string remoteIP = "216.123.23.98"; // For example
var tcpAddress = string.Format("tcp://{0}:8100", remoteIP); // I also tried localhost address here
Console.WriteLine("I: Binding on {0}", tcpAddress);
backend.Bind(tcpAddress);
var epgmAddress = string.Format("epgm://localhost;{0}:8100", remoteIP);
Console.WriteLine("I: Binding on {0}", epgmAddress);
backend.Bind(epgmAddress);
using (var subscription = ZFrame.Create(1))
{
subscription.Write(new byte[] { 0x1 }, 0, 1);
backend.Send(subscription);
}
// Run the proxy until the user interrupts us
ZContext.Proxy(frontend, backend);
}
客户:
using (var context = new ZContext())
using (var subscriber = new ZSocket(context, ZSocketType.SUB))
{
string remoteIP = "tcp://216.123.23.98"; //For example
Console.WriteLine("I: Connecting to {0}…", remoteIP);
subscriber.Connect(connect_to);
// Subscribe to zipcode
string zipCode = args[0];
Console.WriteLine("I: Subscribing to zip code {0}…", zipCode);
subscriber.Subscribe(zipCode);
// Process 10 updates
int i = 0;
long total_temperature = 0;
for (; i < 20; ++i)
{
ZError err;
using (var replyFrame = subscriber.ReceiveFrame(out err))
{
string reply = replyFrame.ReadString(Encoding.ASCII);
Console.WriteLine(reply);
total_temperature += Convert.ToInt64(reply.Split(' ')[1]);
}
}
Console.WriteLine("Average temperature for zipcode '{0}' was {1}", zipCode, (total_temperature / i));
}
当我运行它时,我在服务器中出现错误,在代理中出现错误 - 服务器得到
Invalid end point
代理得到EINVAL(22)
:
Invalid argument at ZeroMQ.ZSocket.Bind(String endpoint)
> A1:
不,ZeroMQ
是一个无代理的消息传递框架。
A2:
不适用
如何修复代码?
对于TCP/IP情况,所有服务都需要遵守各自的传输类寻址规则 - .bind()
/ .connect()
方法都必须声明IP:PORT#
规范的两个部分(IP
部分的DNS解析有一些帮助,但:PORT#
部分仍然是强制性的)
(源代码在客户端中不满足,参考:
subscriber.Connect(connect_to);
而也应该有一个Proxy
边匹配:PORT#
,即:8100
,指定,用于正确的.connect()
)。
为清楚起见并避免port#
冲突,请从代码中删除epgm
传输类。