#include <iostream>
#include <zmq.hpp>
#include <string>
#include <string>
using namespace std;
using std::cout;
using std::endl;
using std::cin;
//-----------------------------------------------------------------------------
int server()
{
cout << "===============Server============" << endl;
zmq::context_t context(1);
zmq::socket_t server(context, ZMQ_REP);
server.bind("tcp://*:6889");
while (1) {
// receive msg
zmq::message_t recvMsg;
server.recv(&recvMsg);
string recievedStr = string(static_cast<char*>(recvMsg.data()), recvMsg.size());
cout << ">>>> get client message:"<< recievedStr << endl;
// send msg
string reply = "I have a dream today !";
zmq::message_t semdMsg(reply.size());
memcpy(semdMsg.data(), semdMsg.data(), semdMsg.size());
server.send(semdMsg);
}
return 0;
}
//-----------------------------------------------------------------------------
int client()
{
cout << "===============Client============" << endl;
// connect
zmq::context_t context(1);
zmq::socket_t *client = new zmq::socket_t (context, ZMQ_REQ);
client->connect("tcp://localhost:6889");
int linger = 0;
client->setsockopt (ZMQ_LINGER, &linger, sizeof (linger));
// send
string reply = "hello";
zmq::message_t messageS(reply.size());
memcpy(messageS.data(), reply.data(), reply.size());
client->send(messageS);
// receive
zmq::message_t messageR;
client->recv(&messageR);
string recieved = string(static_cast<char*>(messageR.data()), messageR.size());
// close
client->close();
delete client;
zmq_term(&context);
return 0;
}
int main(int argc, char* argv[])
{
if (argc == 1) server();
else client();
return 0;
}
|