... | ... | @@ -170,6 +170,65 @@ You can notice that no port was provided to define the requester and responder. |
|
|
|
|
|
Be careful, the responder must receive requests in a loop after *init()* otherwise any requester will block when initializing.
|
|
|
|
|
|
Notice that the responder can reply many times for the same request. The requester must then have as many receive() calls as the number of replies.
|
|
|
|
|
|
Notice that we presented the basic responder which cannot process requests in parallel. A single thread must be used to receive and reply. If you need to process the requests in parallel, then you have to create some multi responders.
|
|
|
|
|
|
# Multi responders
|
|
|
|
|
|
To process the requests in parallel, a set of multi responders must be created. They are attached to a responder router.
|
|
|
|
|
|
An example of multi responders in a Java application:
|
|
|
```java
|
|
|
try {
|
|
|
// Create the router.
|
|
|
ResponderRouter router = ResponderRouter.create("the-responder");
|
|
|
router.init();
|
|
|
|
|
|
// Create 5 multi responders.
|
|
|
for (int i = 0; i < 5; ++i) {
|
|
|
Thread thread = new Thread(new Runnable() {
|
|
|
public void run() {
|
|
|
|
|
|
Responder responder = null;
|
|
|
|
|
|
try {
|
|
|
// Create the multi responder by associating it to the router.
|
|
|
responder = Responder.create(router);
|
|
|
responder.init();
|
|
|
|
|
|
// Receive requests.
|
|
|
while (!responder.isCanceled()) {
|
|
|
Request request = responder.receive();
|
|
|
System.out.println("Received request " + request.getString());
|
|
|
|
|
|
// Reply.
|
|
|
request.replyString("Response");
|
|
|
}
|
|
|
|
|
|
responder.terminate();
|
|
|
}
|
|
|
catch (InitException e) {
|
|
|
}
|
|
|
}
|
|
|
});
|
|
|
|
|
|
thread.start();
|
|
|
}
|
|
|
|
|
|
// Start the router by a blocking call.
|
|
|
router.run();
|
|
|
|
|
|
// Terminate the router once finished.
|
|
|
router.terminate();
|
|
|
}
|
|
|
catch (InitException e) {
|
|
|
}
|
|
|
|
|
|
```
|
|
|
Once the router is receiving a request from a requester, it forwards it to a multi responder (round-robin distribution) that can process it in its own thread. It can also reply multiple times. The router run() call is blocking and the router must be canceled to return.
|
|
|
|
|
|
|
|
|
# Publisher/Subscriber
|
|
|
|
|
|
Another useful communication pattern is the publish/subscribe pattern. It allows asynchronous messages from one application to other ones. Let's define a Java application *PubJava* which defines a publisher:
|
... | ... | |