Messages Structure
Messages in AgE are similar to JMS and other messaging systems. They consist in a header and a payload.
|
Creating Messages
You can easily create messages using utility functions from the org.jage.communication.message.Messages
class:
UnicastSelector<IAddress> selector = Selectors.unicastFor(targetAddress); Message<IAddress, String> message = Messages.newUnicastMessage(myAddress, selector, "Hello world!");
Sending Messages
To send a message between agents, use methods available in the environment:
doAction(AgentActions.sendMessage(message));
As you can see, message delivery is considered as an action. It means that its execution will be deferred until the end of the current step. The intended consequence is that messages sent in one step will be only made available to their receivers in the next step.
In turn, to send messages between components in different nodes, use the communication service:
@Inject private CommunicationService communicationService; ... communicationService.send(message);
Receiving Messages
Every agent is provided with a message queue. Agent receive messages actively by querying their message queue:
import static com.google.common.collect.Iterables.consumingIterable; ... for (IMessage<AgentAddress, ?> message : consumingIterable(getMessages())) { read(message); }
Note the usage of Guava consumingIterable, which removes messages from the queue as they are iterated upon.