Skip to content

Instantly share code, notes, and snippets.

@tell
Last active September 5, 2015 15:40
Show Gist options
  • Save tell/c046caddaa2d0fdc581f to your computer and use it in GitHub Desktop.
Save tell/c046caddaa2d0fdc581f to your computer and use it in GitHub Desktop.
Excersize of ZMQ and MessagePack
//
// Hello World client in C++
// Connects REQ socket to tcp://localhost:5555
// Sends "Hello" to server, expects "World" back
//
#include <zmq.hpp>
#include <msgpack.hpp>
#include <string>
#include <iostream>
int main () {
msgpack::sbuffer buffer;
msgpack::packer<decltype(buffer)> pk(&buffer);
pk.pack("Hello");
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REQ);
std::cout << "Connecting to server ..." << std::endl;
socket.connect ("tcp://localhost:5555");
// Do 10 requests, waiting each time for a response
for (int i = 0; i != 10; i++) {
zmq::message_t request(buffer.size());
memcpy((void *) request.data(), buffer.data(), buffer.size());
std::cout << "<--- sending " << i << " times" << std::endl;
socket.send(request);
// Get the reply.
zmq::message_t reply;
socket.recv(&reply);
std::cout << "---> received " << i << " times" << std::endl;
}
return 0;
}
//
// Hello World server in C++
// Binds REP socket to tcp://*:5555
// Expects "Hello" from client, replies with "World"
//
#include <zmq.hpp>
#include <msgpack.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://*:5555");
size_t ctr = 0;
while (true) {
ctr++;
zmq::message_t request;
// Wait for next request from client
socket.recv (&request);
std::cout << "Received Hello " << ctr << " times" << std::endl;
std::cout << "The size is " << request.size() << std::endl;
#if 0
msgpack::unpacker upk;
upk.reserve_buffer(request.size());
memcpy(upk.buffer(), request.data(), request.size());
upk.buffer_consumed(request.size());
msgpack::unpacked result;
upk.next(&result);
#endif
msgpack::unpacked result;
msgpack::unpack(&result, (const char*)request.data(), request.size());
std::cout << "Received message is: " << result.get() << 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;
}
CXXFLAGS = -std=c++11
LDLIBS = -lzmq
TARGETS = hwserver hwclient
all: $(TARGETS)
clean:
$(RM) $(TARGETS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment