Reference: http://iyuan.iteye.com/blog/973013
The publishing and subscription roles here are absolute, that is, the publisher cannot use Recv, the subscriber cannot use send, and the subscriber needs to set the subscription condition "setsockopt ".
According to the official website, in this mode, data released when the publisher is just started may be lost because zmq is too fast to send data. When the subscriber has not established a contact with the publisher, data publishing has started (internal LAN is not so exaggerated ). The official website provides two solutions. 1. The publisher sleep and sends data later (marked as stupid); 2, if it is found later, it will be updated here ).
UpperCode: Publisher:
Package COM. zeromq. test. sync_pub_sub; import Org. zeromq. zmq; import Org. zeromq. zmq. context; import Org. zeromq. zmq. socket;/*** @ author Lu Gui strong * @ email larry.lv.word@gmail.com * @ version Creation Time: 8:17:40 */public class syncpub {// wait for 10 subscribers protected static int subscribers_expected = 10; public static void main (string [] ARGs) {context = zmq. context (1); socket publisher = context. socket (zmq. pub); Publisher. BIND ("TCP: // *: 5561"); try {// zmq transmission speed is too fast. When the subscriber has not established a contact with the publisher, the data publishing thread has started. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} int update_nbr; For (update_nbr = 0; update_nbr <10; update_nbr ++) {publisher. send ("rhubarb ". getbytes (), zmq. noblock);} publisher. send ("end ". getbytes (), 0); Publisher. close (); context. term ();}}
Subscriber:
Package COM. zeromq. test. sync_pub_sub; import Org. zeromq. zmq; import Org. zeromq. zmq. context; import Org. zeromq. zmq. socket;/*** @ author Lu Gui strong * @ email larry.lv.word@gmail.com * @ version Creation Time: 8:36:42 */public class syncsub {public static void main (string [] ARGs) {context = zmq. context (1); socket subscriber = context. socket (zmq. sub); subscriber. connect ("TCP: // localhost: 5561"); subscriber. subscribe ("". getbytes (); int update_nbr = 0; while (true) {byte [] stringvalue = subscriber. recv (0); string = new string (stringvalue); If (string. equals ("end") {break;} update_nbr ++; system. out. println ("received" + update_nbr + "updates.: "+ String);} subscriber. close (); context. term ();}}