分类: Java
2007-06-02 08:39:31
在JADE中,支持agents之间通信的消息内容使用序列化的java对象,对本地应用,特别是所有agent都用java实现的情况下也是很有用的.
看实例:一个ObjectSender负责发送一个Person对象,ObjectReceiver负责接收后打印出接收到的内容。
源文件:Person.java
package examples.Base64;
import java.io.*;
import java.util.Date;
public class Person implements Serializable {
String name;
String surname;
Date birthdate;
int age;
Person(String n,
String s, Date d, int a) {
name = n;
surname = s;
birthdate = d;
age = a;
}
return(name+ " "+ surname +" born on
"+birthdate.toString()+" age = "+age);
}
}
文件2:ObjectSender.java
package examples.Base64;
import java.io.IOException;
import java.util.Date;
import jade.core.*;
import
jade.lang.acl.ACLMessage;
public class ObjectSender extends Agent {
protected void setup()
{
try{
ACLMessage
msg = new ACLMessage(ACLMessage.INFORM);
msg.setContent(
"
AID
personR = new AID( "personR", AID.ISLOCALNAME );
msg.addReceiver(personR
);
Person p
= new Person("Name1", "Surname1", new Date(), 1);
msg.setContentObject(p);
msg.setLanguage("JavaSerialization");
send(msg);
System.out.println(getLocalName()+" sent 1st msg
"+msg);
send(msg);
}
catch (IOException e ) {
e.printStackTrace();
}
doDelete(); // kill itself
because it has completed its task.
}
}
文件三:ObjectReceiver.java
package examples.Base64;
import jade.core.*;
import
jade.core.behaviours.CyclicBehaviour;
import
jade.lang.acl.ACLMessage;
import
jade.lang.acl.UnreadableException;
public class ObjectReceiver extends Agent {
protected void setup() {
addBehaviour(new CyclicBehaviour(this)
{
public void action() {
try{
ACLMessage msg = blockingReceive();
System.out.println(getLocalName()+
"
rx msg"+msg);
if ("JavaSerialization".equals(msg.getLanguage()))
{
Person p = (Person)msg.getContentObject();
System.out.println(getLocalName()+
"
获取Java对象: ");
System.out.println(p.getClass().getName());
System.out.println(p.toString());
}
}
catch(UnreadableException
e3){
System.err.println(getLocalName()+
"
catched exception "+e3.getMessage());
}
block();
}
});
}
}