javaagentagents-jade

How to make agents communicate in jade?


I want my first Agent to send a message to the second Agent, this is the code for the First agent :

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

public class First extends Agent {  

@Override
protected void setup() {
    addBehaviour(new OneShotBehaviour() {
        
        @Override
        public void action() {
            System.out.println("I'm sending");
            ACLMessage msg =new ACLMessage(ACLMessage.INFORM);
            msg.addReceiver(new AID("second",AID.ISLOCALNAME));
            msg.setContent("HELLO");
            send(msg);              
        }
    });
}}

And for the second class :

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

public class Second extends Agent {
 
@Override
protected void setup() {
    addBehaviour(new CyclicBehaviour() {
        
         @Override
         public void action() {
             ACLMessage msg = receive();
             if(msg != null) {
                 System.out.print("i received "+msg.getContent());
             } else {
                 System.out.print("i didn't receive msg ");
                 block();
             }               
         }
    });
}}

But the second agent always execute the else statement and msg seems to be null, and i can't figure why.

Any suggestion ?

Thanks


Solution

  • This line below

    
    ACLMessage msg = receive();
    
    

    only reads a message from the messages queue of the agnet. It does not wait to receive a message. So, your second agent is being executed before that he receives the message, that's why the else is executed at first.

    However,

    But the second agent always execute the else statement and msg seems to be null, and i can't figure why.

    This is not correct, the else statement is executed at first, then the agent prints its message, then the else is exectued again, then the agents is blocked.

    The explanation: your first agent has a OneShotBehaviour, that means that he will execute his code once and then quite. That being said, he will send his message only one time.

    While your second agent has a CyclicBehaviour, that means that he will keep repeating himself. In the first run of this behaviour, the else is executed because the message was not received yet. Then, there is the block which will block this behaviour until a message is received. When the message is received, the behaviour will repeat itself, but this time he will print the received message. Then the block again...

    If you want your second agent to print the message from the first time, you need to make your agent waits to receive a message. You can use the method doWait() before the line above. This way, your second agent will keep waiting until he receives a message.

    
    doWait();
    
    ACLMessage msg = receive();