ZeroMQ guide-Chapter 2-basics-publish messages

Source: Internet
Author: User

The second Classic Mode for releasing messages is one-way data distribution. The server pushes updates to a group of clients. Let's take a look at an example of pushing weather changes, including the region code, temperature, and relative humidity. We generate a random value to simulate a real weather station. This is the server code. We use port 5556 for this program. Wuserver: Weather update server in C [cpp] /// Weather update server // Binds PUB socket to tcp ://*: 5556 // Publishes random weather updates // # include "zhelpers. h "int main (void) {// Prepare our context and publisher void * context = zmq_ctx_new (); void * publisher = zmq_socket (context, ZMQ_PUB ); int rc = zmq_bind (publisher, "tcp: // *: 5556"); assert (rc = 0); rc = zmq_bind (publisher, "ipc :// Weather. ipc "); assert (rc = 0); // Initialize random number generator srandom (unsigned) time (NULL); while (1) {// Get values that will fool the boss int zipcode, temperature, relhumidity; zipcode = randof (100000); temperature = randof (215)-80; relhumidity = randof (50) + 10; // Send message to all subscribers char update [20]; sprintf (update, "% 05d % d", zipcode, temperature, relhumid Ity); s_send (publisher, update);} zmq_close (publisher); zmq_ctx_destroy (context); return 0;} the update stream has neither started nor ended, like a weather forecast that never ends. Figure 4-publish-subscribe this is a client program that listens to the update stream and captures all messages that conform to the encoding of a specific region. The default value is New York City because it is a good place to take an adventure: wuclient: weather update client in C [cpp] /// Weather update client // Connects SUB socket to tcp: // localhost: 5556 // Collects weather updates and finds avg temp in zipcode // # include "zhelpers. h "int main (int argc, char * argv []) {void * context = zmq_ctx_new (); // Socket to talk to server printf (" Collecting updates from weather serv Er... \ N "); void * subscriber = zmq_socket (context, ZMQ_SUB); int rc = zmq_connect (subscriber," tcp: // localhost: 5556 "); assert (rc = 0); // Subscribe to zipcode, default is NYC, 10001 char * filter = (argc> 1 )? Argv [1]: "10001"; rc = zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE, filter, strlen (filter); assert (rc = 0 ); // Process 100 updates int update_nbr; long total_temp = 0; for (update_nbr = 0; update_nbr <100; update_nbr ++) {char * string = s_recv (subscriber); int zipcode, temperature, relhumidity; sscanf (string, "% d", & zipcode, & temperature, & relhumidity); total_temp + = temperature; fre E (string);} printf ("Average temperature for zipcode '% s' was % dF \ n", filter, (int) (total_temp/update_nbr )); zmq_close (subscriber); zmq_ctx_destroy (context); return 0;} note that when you use a subscription socket, you must use zmq_setsockopt () and SUBSCRIBE to set a subscription, as in this Code. If you do not set any subscription, you will not receive any messages. This is a common mistake for beginners. Subscriber can set many subscriptions and merge them together. That is to say, if an update matches any subscription, the subscriber will receive it. A subscriber can also cancel a specific subscription. A subscription is usually a printable string, but it is not required. See zmq_setsockopt () to see how this works. The Publish and subscribe socket pair is asynchronous. The client performs zmq_msg_recv () in a loop (or if necessary (). An error occurs when you try to send a message to the subscription socket. Similarly, the Service performs zmq_msg_send () at the required frequency, but zmq_msg_recv () cannot be performed on the published socket (). Theoretically, the MQ socket does not care which end is connected and bound. However, there will be undisclosed differences in practice, which will be mentioned later. Now, bind the release and connect to the subscription, unless your network design causes this to fail. Another important thing about publishing and subscription sockets is that you cannot know exactly when the subscriber starts to get messages. Even if you start a subscriber and start the publisher later, the subscriber will always miss the first message sent by the publisher. This is because when the subscriber connects to the publisher (which takes a short but non-zero time), the publisher may have sent the message. This "Slow entrant" symptom has hit many people and many times. We need to explain it in detail. Remember that MQ is asynchronous I/O, that is, in the background. For example, you have two nodes in this order: the subscriber connects to an endpoint and receives and counts the message. The Subscriber binds to an endpoint and immediately sends 1000 messages. Then, the subscriber may not receive anything. You can check if a filter is set correctly and try again. However, the subscriber still does not receive anything. Establishing a TCP connection involves several milliseconds of round-trip handshake, depending on the network condition and the number of hops between nodes. During this time, MQ has been able to send many messages. To prove that it takes five milliseconds to establish a connection, and the same link can handle 1 Mbit/s of messages. Within five milliseconds after a subscriber connects to the publisher, the publisher only sends the 1 K message in 1 ms. In Chapter 2nd-socket and mode, we will explain how to synchronize publishers and subscribers so that data can be published without waiting for the subscribers to be connected and ready. There is a simple and stupid way to delay publishers by sleep. But do not do this in real programs, because it is extremely fragile, indecent and slow. First use sleep to prove to yourself what happened, and then wait until Chapter 1 to see the correct practice. Another alternative to synchronization is to simply assume that the released data stream is infinite and has not ended since the beginning. It is also assumed that the subscriber does not care about what happened before it starts. This is how we built the weather client. The client subscribes to the selected region code and collects 1000 updates. That is, about 10 million server updates, if the region code is randomly distributed. You can start the client first and then start the server, and the client will continue to work. You can stop and restart the server at any time, and the client will continue to work. When the client collects 1000 updates, it calculates the average value, prints the output, and then exits. Key points about the publishing and subscription mode: The subscriber can call "connect" each time to connect to more than one publisher. Data is staggered ("fair queue") to prevent publishers from flooding each other. If a publisher does not have a connected subscriber, it directly discards all messages. If a subscriber is slow when you use TCP, messages will be queued at the publisher. We will see how to use the "high water level line" to protect publishers in this case. Starting from MQ 3.x, using the connected protocol (tcp: Or ipc :) will filter the publisher. When using the epgm: // protocol, the filter will be performed on the subscriber side. In Ø MQ2. x, all filters are performed on subscribers. The following figure shows how long it takes to filter 10 m messages in my laptop. The computer configuration is 2011-era Intel i5, Which is decent but not special. [Plain] $ time wuclient Collecting updates from weather server... Average temperature for zipcode '000000' was 28F real 0m4. 10001 s user 0m0. 000 s sys 0m0. 008 s

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.