3

I have a RequestSocket on the client side sending requests to a server. The server must be able to handle requests in parallel so I have used a RouterSocket with a poller.

I am unsure if this is the best implementation since it uses a fair amount of CPU while there are no requests to handle? Specifically the SendReady event on the RouterSocket is triggerd extremely often.

class Program
{
    static ConcurrentQueue<NetMQMessage> outgoingQueue = new ConcurrentQueue<NetMQMessage>();

    static void Main(string[] args)
    {
        var poller = new Poller();
        using (var context = NetMQContext.Create())
        using (var router = context.CreateRouterSocket())
        {
            router.Bind("tcp://127.0.0.1:1337");
            poller.AddSocket(router);

            router.ReceiveReady += (s, a) => HandleRequest(a.Socket.ReceiveMessage());

            router.SendReady += (s, a) =>
            {

                if (!outgoingQueue.IsEmpty)
                {
                    NetMQMessage msg;
                    if (outgoingQueue.TryDequeue(out msg))
                    {
                        a.Socket.SendMessage(msg);
                        Console.WriteLine("Sent: " + msg[2].ConvertToString());
                    }
                }
            };
            poller.Start();
        }
    }

    static void HandleRequest(NetMQMessage requestMsg)
    {
        Console.WriteLine("Received: " + requestMsg[2].ConvertToString());
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            NetMQMessage responseMsg = new NetMQMessage();
            responseMsg.Append(requestMsg[0]);
            responseMsg.AppendEmptyFrame();
            responseMsg.Append("Enjoy " + requestMsg[2].ConvertToString());
            outgoingQueue.Enqueue(responseMsg);
        });
    }
}
OMGKurtNilsen
  • 5,048
  • 7
  • 27
  • 36

2 Answers2

2

You should not use SendReady, it will invoke every time since router is always ready to send. As suggested try to read the polling guide. Also read about NetMQScheduler, you can use it instead of the ConcurrentQueue.

http://somdoron.com/2013/06/netmq-scheduler/

somdoron
  • 4,653
  • 2
  • 16
  • 24
0

It is possible to add a timer to a socket you are polling to control the frequency of polling as the netMQ guide specify :

If you wish to perform some operation periodically, and need that operation to be performed on a thread which is allowed to use one or more sockets, you can add a NetMQTimer to the Poller along with the sockets you wish to use.

try this link for more information: NetMQ guide - Polling

barakcaf
  • 1,294
  • 2
  • 16
  • 27