This article attempts to use zeromq to complete a simple network transfer task.
(Tom uses the open-source shared library (C uses zeromq). This article has completed a simple and runable BASIC Program. This article is based on this transformation)
The modified content of Main. C is as follows:
#include "zhelpers.h"int main (void){ void *context = zmq_init (1); // Socket to talk to clients void *responder = zmq_socket (context, ZMQ_REP); zmq_bind(responder, "tcp://*:5559"); while (1) { // Wait for next request from client char *string = s_recv (responder); printf ("Received request: [%s]\n", string); free (string); // Do some 'work' sleep (1); // Send reply back to client s_send (responder, "World"); } // We never get here but clean up anyhow zmq_close(responder); zmq_term(context); return 0;}
Of course, we also need a client. C to act as the client, and create client. C under the main. c directory at the same level. In the same way, add the client compilation information to makefile.
//// Hello World client// Connects REQ socket to tcp://localhost:5559// Sends "Hello" to server, expects "World" back//#include "zhelpers.h"int main (void){ void *context = zmq_init (1); // Socket to talk to server void *requester = zmq_socket (context, ZMQ_REQ); zmq_connect (requester, "tcp://localhost:5559"); int request_nbr; for (request_nbr = 0; request_nbr != 10; request_nbr++) { s_send (requester, "Hello"); char *string = s_recv (requester); printf ("Received reply %d [%s]\n", request_nbr, string); free (string); } zmq_close (requester); zmq_term (context); return 0;}
This is the code found on the zeromq official website. It may have a small problem and it can run smoothly after a slight transformation. The original Article is here
Https://github.com/imatix/zguide/blob/master/examples/C/rrserver.c
Https://github.com/imatix/zguide/blob/master/examples/C/rrclient.c
Note that the program uses a zhelpers. h header file, which is also available on the official website. If you need it, find it by yourself.
Copy the image to include without moving it, and return to make in the app.
Start two putty instances, one running main and the other running client. The following figure shows the effect.
To sum up
1. Just a few lines of code can complete basic socket communication, and the strength of zmq has been reflected.
2 open source is really a good thing. Happiness comes from sharing.