pBook‎ > ‎ZMQ‎ > ‎

Example client server

posted May 29, 2016, 6:07 AM by Javad Taghia   [ updated May 29, 2016, 6:09 AM ]
#SERVER
//  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>
#ifndef _WIN32
#include <unistd.h>
#else
#include <windows.h>

#define sleep(n)    Sleep(n)
#endif

int main () {
    //  Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REP);
    socket.bind ("tcp://*:9998");

    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 (reply.data (), "World", 5);
        socket.send (reply);
    }
    return 0;
}

#CLIENT
#include <zmq.hpp>
#include <string>
#include <iostream>
#ifndef _WIN32
#include <unistd.h>
#else
#include <windows.h>

#define sleep(n)    Sleep(n)
#endif

int main ()
{
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REQ);

socket.connect("tcp://127.0.0.1:9998");

while (true)
{

  //  Do some 'work'
        sleep(10);

      zmq::message_t reply (5);
        memcpy (reply.data (), "World", 5);
socket.send( reply);
zmq::message_t request;
  //  Wait for next request from client
        socket.recv (&request);
        std::cout << "Received Hello" << std::endl;
}
return 0;
}
Comments