Search code examples
zeromqnetmq

ZeroMQ choose recipient


I'm new to ZeroMQ (and to networking in general), and have a question about using ZeroMQ in a setup where multiple clients connect to a single server. My situation is as follows:

--1 server
--multiple clients

--Clients send messages to server: I've already figured out how to do this part.
--Server sends messages to a specific client: This is the part I'm having trouble with. When certain events get handled on the server, the server will need to send a message to a specific client -- not all clients. In other words, the server will need to be able to choose which client to send a given message to.

Right now, this is my server code:

using (NetMQContext ctx = NetMQContext.Create())
{
    using (var server = ctx.CreateResponseSocket())
    {
        server.Bind(@"tcp://127.0.0.1:5555");
        while (true)
        {
            string fromClientMessage = server.ReceiveString();
            Console.WriteLine("From Client: {0}", fromClientMessage);

            server.Send("ack"); // There is no overload for the 'Send'
                                   method that takes an IP address as an argument!
        }
    }
}

I have a feeling that the problem is that my design is wrong, and that the ResponseSocket type isn't meant to be used in the way that I want to use it. Since I'm new to this, any advice is very much appreciated!


Solution

  • when using the Response socket you always replying to the client that sent you the message. So the Request-Response socket types together are just simple request response.

    To more complicated scenarios you probably want to use Dealer-Router.

    With router the first frame of each message is the routing id (the identity of the client that sent you the message)

    so your example with router will look like:

    using (NetMQContext ctx = NetMQContext.Create())
    {
        using (var server = ctx.CreateRouterSocket())
        {
            server.Bind(@"tcp://127.0.0.1:5555");
            while (true)
            {
                byte[] routingId = server.Receive();
                string fromClientMessage = server.ReceiveString();
                Console.WriteLine("From Client: {0}", fromClientMessage);
    
                server.SendMore(routingId).Send("ack");
            }
        }
    }
    

    I also suggest to read the zeromq guide, it will probably answer most of your questions.