【问题标题】:Why cannot get the ZeroMQ ROUTER / ROUTER pattern to work?为什么不能让 ZeroMQ ROUTER / ROUTER 模式工作?
【发布时间】:2016-12-31 04:39:29
【问题描述】:

我正在尝试使用 ZeroMQ 在 VS 中实现 ROUTER / ROUTER 模式,但我似乎无法让事情正常工作。据我所知,我知道服务器工作正常,因为我尝试使用其他类型的客户端套接字没有任何问题。但是在将其设为ROUTER 时,它不起作用。

有人知道如何修复客户端吗?

我的代码如下:

static string ip = "127.0.0.1";
static string port = "5555";
static string endpoint = string.Format("tcp://{0}:{1}", ip, port);

static void Main(string[] args)
    {
        Task.Factory.StartNew(StartRouterServer,TaskCreationOptions.LongRunning);
        Task.Factory.StartNew(() => StartRouterClient(0), TaskCreationOptions.LongRunning);

        Thread.Sleep(10000000);
    }

static void StartRouterClient(int i)
    {
        using (ZContext context = new ZContext())
        using (ZSocket router = new ZSocket(context, ZSocketType.ROUTER))
        {
            router.IdentityString = "client: " + i;
            router.Connect(endpoint);
            //send message
            router.SendMore(new ZFrame(router.IdentityString));
            router.SendMore(new ZFrame());
            router.Send(new ZFrame("Hi"));

            using (ZMessage received = router.ReceiveMessage())
            {//on receiving a reply from the server, you come here.
                Console.WriteLine("Received a message back from the server!!");
            }
        }
    }

static void StartRouterServer()
    {
        using (ZContext context = new ZContext())
        using (ZSocket router = new ZSocket(context, ZSocketType.ROUTER))
        {
            router.IdentityString = "router";
            router.Bind(endpoint);
            Console.WriteLine("The server is bound to {0}", router.LastEndpoint);

            while (true)
            {
                using (ZMessage received = router.ReceiveMessage())
                {//what you do when you receive the message.
                    Console.WriteLine("received a message!");
                    router.SendMore(received[0]);
                    router.SendMore(new ZFrame());
                    router.Send(new ZFrame("Hi back!!"));
                }
            }
        }
    }

【问题讨论】:

    标签: c# zeromq


    【解决方案1】:

    客户端套接字可能在服务器套接字绑定到端口 5555 之前创建并尝试发送。如果发生这种情况,客户端套接字将丢弃消息。

    尝试在对Task.Factory.StartNew() 的调用之间放置一个Thread.Sleep( 1000 ),以允许创建和绑定服务器套接字。

    (我在python中写了一个类似的代码并且它可以工作,只要在客户端连接和发送之前确定服务器套接字就可以了。)

    【讨论】:

    • 我试过了。不工作。这是我搞砸的地址。不过谢谢你的帮助!
    【解决方案2】:

    好的,nvm,我搞砸了地址。对于这种模式,每个路由器都需要知道彼此的身份。这就是它的工作方式。 即在 StartRouterClient() 方法中, 我不得不更换router.SendMore(new ZFrame(router.IdentityString)); router.SendMore(server.IdentityString);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 2017-04-14
      • 2018-02-25
      • 2020-01-30
      • 1970-01-01
      • 2021-09-25
      • 2017-09-22
      相关资源
      最近更新 更多