Reputation: 1371
I am trying Zeromq Hello world example for server and client. below is the example code
//
// Hello World client in C++
// Connects REQ socket to tcp://localhost:5555
// Sends "Hello" to server, expects "World" back
//
#include <zmq.hpp>
#include <string>
#include <iostream>
int main ()
{
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REQ);
std::cout << "Connecting to hello world server…" << std::endl;
socket.connect ("tcp://localhost:5555");
// Do 10 requests, waiting each time for a response
for (int request_nbr = 0; request_nbr != 10; request_nbr++) {
zmq::message_t request (6);
memcpy ((void *) request.data (), "Hello", 5);
std::cout << "Sending Hello " << request_nbr << "…" << std::endl;
socket.send (request);
// Get the reply.
zmq::message_t reply;
socket.recv (&reply);
std::cout << "Received World " << request_nbr << std::endl;
}
return 0;
}
and the Server code
//
// Hello World server in C++
// Binds REP socket to tcp://*:5555
// Expects "Hello" from client, replies with "World"
//
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>
int main () {
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REP);
socket.bind ("tcp://*:5555");
while (true) {
zmq::message_t request;
// Wait for next request from client
socket.recv (&request);
std::cout << "Received Hello" << std::endl;
// Do some 'work'
sleep (1);
// Send reply back to client
zmq::message_t reply (5);
memcpy ((void *) reply.data (), "World", 5);
socket.send (reply);
}
return 0;
}
The Code works fine I am able to send the request and get the reply.
But I want that the server should not wait for the request from the client .The server continue running and if the request from the client come it give the reply.
What changes can I make in the program to achieve this.
Upvotes: 1
Views: 6553
Reputation: 3660
You can try the ZMQ_PUSH/ZMQ_PULL
combination to make the client requests non-blocking.
If you want to go beyond hello world, you might want to look at the architecture of the Push Framework. What do you mean by letting the server to continue running? Do you mean multithreading? Most probably you don't want to do that. If you want to scale your application to lots of clients, you should probably check out load balancing
The server socket will collect the messsages asynchronously for you in the background by itself. What you typically do is that you collect the messages serially in one place of the server and dispatch the reactions to the messages for further processing as you wish - asynchronously or not.
Upvotes: 0
Reputation: 920
You need to work with thread to do this. For an example with Boost thread http://thisthread.blogspot.fr/2011/08/multithreading-with-zeromq.html
Upvotes: 0