The previous article introduced the simpler Request/subscribe mode, this article introduces the more classical Publish/subscribe communication mode used to zeromq the implementation, its communication method is as follows figure:
The client (subscriber) subscribes to the server (publisher), and the server can then push the message to all clients that subscribe to the message, which can also be understood as broadcast bar ....
Well, gossip does not say much, directly on the use of ZEROMQ to implement this communication mode code:
(1) server side (publisher):[Java] view plaincopy package pubsub; import org.zeromq.zmq; public class publisher { public Static void main (string args[]) { zmq. Context context = zmq.context (1); //Create a context that contains an I/O thread zmq. Socket publisher = context.socket (ZMQ. PUB); //creates a publisher-type socket that he can broadcast data to all subscribed subscriber publisher.bind ("tcp://* : 5555 "); //bind current publisher to Port 5555 to accept Subscriber subscriptions while (! Thread.currentthread () .isinterrupted ()) { String message = "Fjs hello" //the first can be understood as pub channel, Subscribe need to subscribe to FJS this channel to receive messages publisher.send (Message.getbytes ()); } publisher.close (); context.term (); } }
The code is very simple, here Publisher to serve as the server, all subscriber need to build a connection to Publisher. ,,。 ,
(2) Client (subscriber) code:[Java] view plaincopy package pubsub; import org.zeromq.zmq; public class subscriber { public static void main (string args[]) { for (int j = 0; j < 100; j++) { new thread (new runnable () { public void run () { // TODO Auto-generated method stub zMq. Context context = zmq.context (1); //Create 1 I/O threads context zmq. Socket subscriber = context.socket (ZMQ. Sub); //creates a sub type, which is the subscriber type of socket Subscriber.connect ("tcp://127.0.0.1:5555") //connection with Publisher listening on port 5555 subscriber.subscribe ("Fjs". GetBytes ()); //Subscribe FJS this channel