How to process messages async i RouterSocket?

307 views
Skip to first unread message

Erik Zetterqvist

unread,
Aug 20, 2015, 5:14:02 AM8/20/15
to netmq-dev
I try to process messages asynchronously in my server using the code below. If I use a request socket and send ONE request to this server it prints out a lot of "Starts a new Task to process the request." messages from the ReceiveReady-event.
To mee it seems like the poller raises to many events. Why? Whats wrong with my code?

Thank you!


            using (var context = NetMQContext.Create())
            using (var server = context.CreateRouterSocket())
            using (var poller = new Poller())
            {
                server.Bind(string.Format("tcp://localhost:{0}", PortNumber));

                server.ReceiveReady += (s, a) =>
                {
                    Console.WriteLine("Starts a new Task to process the request.");
                    Task.Factory.StartNew(() =>
                    {
                        var identity = a.Socket.ReceiveFrameString();
                        var empty = a.Socket.ReceiveFrameString();
                        var message = a.Socket.ReceiveFrameString();

                        Console.WriteLine("Received message from: {0}, message: {1}", identity, message);

                        a.Socket.SendMoreFrame(identity);
                        a.Socket.SendMoreFrameEmpty();
                        a.Socket.SendFrame("ACK from server");
                    });
                };

                poller.AddSocket(server);
                poller.PollTillCancelledNonBlocking();

                Console.ReadKey();
            }
        }

Erik Zetterqvist

unread,
Aug 20, 2015, 10:33:07 AM8/20/15
to netmq-dev
My bad!

Now I understand how this works. The poller keeps raising the ReceiveRady evnent as long as there is a message to recieve. Ofcourse :)
Since it takes some time to start the task the event is raised again and again in the mean time.

Doron Somech

unread,
Aug 20, 2015, 11:46:06 AM8/20/15
to Erik Zetterqvist, netmq-dev
Also socket is not thread safe, you are polling on one thread and receive the message on another, that will not work (it might work for some time, but eventually the behavior is unknown).

Why not just handle the message on the event? after receiving the message you can start new task, but you have to make sure you make the Send operation back on the origin thread.

Checkout NetMQScheduler.

--
You received this message because you are subscribed to the Google Groups "netmq-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to netmq-dev+...@googlegroups.com.
To post to this group, send email to netm...@googlegroups.com.
Visit this group at http://groups.google.com/group/netmq-dev.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages