diff --git a/cpp/zmq/req-rep/Makefile b/cpp/zmq/req-rep/Makefile new file mode 100644 index 0000000..b54c035 --- /dev/null +++ b/cpp/zmq/req-rep/Makefile @@ -0,0 +1,12 @@ +server : server.cpp + g++ -o server server.cpp -lzmq +server_arg: server_arg_port.cpp + g++ -o server_arg server_arg_port.cpp -lzmq +client : client.cpp + g++ -o client client.cpp -lzmq +client_connect_to_many : client_connect_multiple_server.cpp + g++ -o client_connect_to_many client_connect_multiple_server.cpp -lzmq + +all: server server_arg client client_connect_to_many client +clean: + rm -f server server_arg client client_connect_to_many client diff --git a/cpp/zmq/req-rep/client_connect_multiple_server.cpp b/cpp/zmq/req-rep/client_connect_multiple_server.cpp new file mode 100644 index 0000000..1cabd5f --- /dev/null +++ b/cpp/zmq/req-rep/client_connect_multiple_server.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include + +using std::cerr; +using std::cout; +using std::endl; + +int main (int argc, char *argv[]) +{ + if (argc < 2){ + cerr << "Usage: " << argv[0] << " server1-port server2-port ... "; + exit(1); + } + + zmq::context_t context (1); + zmq::socket_t socket (context, ZMQ_REQ); + + int i = 1; + char transport[128]; + + while (i < argc) { + snprintf(transport, 128, "tcp://127.0.0.1:%s", argv[i++]); + socket.connect(transport); + } + + while (true){ + zmq::message_t request (1024); + memcpy ((void *) request.data (), "Hello", 6); + socket.send (request); + zmq::message_t reply; + socket.recv (&reply); + cout << "Received " << (char *)reply.data() << endl; + sleep(1); + } + socket.close(); + context.close(); + return 0; +} diff --git a/cpp/zmq/req-rep/server.cpp b/cpp/zmq/req-rep/server.cpp index e8ca736..575ed50 100644 --- a/cpp/zmq/req-rep/server.cpp +++ b/cpp/zmq/req-rep/server.cpp @@ -1,7 +1,6 @@ #include #include #include -#include int main () { zmq::context_t context (1); diff --git a/cpp/zmq/req-rep/server_arg_port.cpp b/cpp/zmq/req-rep/server_arg_port.cpp new file mode 100644 index 0000000..6e2b610 --- /dev/null +++ b/cpp/zmq/req-rep/server_arg_port.cpp @@ -0,0 +1,39 @@ +#include +#include +#include + +using std::cerr; +using std::cout; +using std::endl; + +int main (int argc, char *argv[]) +{ + if (argc != 2) { + cerr << argv[0] << " " << "bind-port" << endl; + exit(1); + } + + char transport[255] = ""; + zmq::context_t context (1); + zmq::socket_t socket (context, ZMQ_REP); + snprintf(transport, 255, "tcp://*:%s", argv[1]); + socket.bind (transport); + + char response[512]; + memset(response, 0, 512); + snprintf(response, 512, "Response from server lisetning on %s", argv[1]); + int i = strlen(response); + int times = 0; + + while (true){ + zmq::message_t request; + socket.recv (&request); + zmq::message_t reply (512); + snprintf(response + i , 512, " #%d", times++); + memcpy ((void *) reply.data (), response, strlen(response)); + socket.send (reply); + } + socket.close(); + context.close(); + return 0; +}