7

I am trying to implement a simple message passing between two applications using NetMQ (a slightly more elaborate description of what I am trying to achieve is below).
After a bit of trial and error I've found that I can't just send or receive messages right away after a Connect/Bind calls, since they are non blocking and actually return even if the connection hasn't been established yet.
For now I solved this with Thread.Sleep(), but this has a bad taste to it and definitely a no-go for a production system.

So the question is, how's one supposed to do it in NetMQ/ZeroMQ?

Client example:

        using (NetMQContext ctx = NetMQContext.Create())
        {
            using (var client = ctx.CreatePushSocket())
            {
                client.Connect("tcp://127.0.0.1:5555");
                Thread.Sleep(100); // wait for connection

                for (int i = 0; i < 5; i++) 
                {
                    client.Send("test " + i , true);
                }
            }
        }
    }

Server example:

    using (NetMQContext ctx = NetMQContext.Create())
    {
        using (var server = ctx.CreatePullSocket())
        {
            server.Bind("tcp://127.0.0.1:5555");
            Thread.Sleep(100); // wait for connection
            while (true)
            {
                var str = server.ReceiveString();
                Console.Out.WriteLine(str);
                Thread.Sleep(60*1000); // do msg processing
            }
        }
    }

Description of what I am trying to achieve:

Client - Sends messages to a single server. The client should not block and should not discard messages when server is not available. The client can come offline/online at any time.

Server - Receives messages from a single client. The server blocks until a message is received. Server needs to do lengthy processing of the message and should not loose any other messages while processing. The server can come offline/online at any time.

4

2 回答 2

10

接收和发送都可以等到可以执行,您将 true 传递给示例中的 dontWait 参数,只需将其删除,它就会在可以时发送消息。

对于接收,您不必睡觉,因为它会等到消息可用。

正如建议使用 Poller 也是一种解决方案(您可以轮询套接字何时可以发送以及何时可以使用消息),请查看 poller 类的测试:https ://github.com/zeromq/netmq/blob /3.3.3-rc5/src/NetMQ.Tests/PollerTests.cs

于 2014-06-22T13:20:12.723 回答
5

在服务器端休眠的最佳解决方案是创建一个套接字轮询器并在拉取套接字上轮询,直到收到消息。这避免了浪费的睡眠,并使代码通常更紧凑。

在客户端,最好的解决方案可能是创建两个套接字(一个用于发送消息,一个用于接收),并让服务器宣布其存在,以便客户端发送消息。因为 ZeroMQ 在处理多个连接方面很有效,所以这个解决方案会很好地工作。

于 2014-03-29T16:26:44.877 回答