序列化和反序列化
把对象转换为字节序列的过程称为对象的序列化。把字节序列恢复为对象的过程称为对象的反序列化。简单说就是为了保存在内存中的各种对象的状态,并且可以把保存的对象状态再读出来。
当两个进程在进行远程通信时,彼此可以发送各种类型的数据。无论是何种类型的数据,都会以二进制序列的形式在网络上传送。发送方需要把这个Java对象转换为字节序列,才能在网络上传送;接收方则需要把字节序列再恢复为Java对象。
在 JADE开发过程中, Agent 之间的通信的消息主要有三种:String, Java Serializable Object, Ontology Object.
JADE 发送/接收基于Java序列化对象,一般需要如下几个操作:
- 定义一个类
- 实现 Serializable接口
- ACLMessage 的 setContentObject() 方法设置发送内容
- ACLMessage 的 getContentObject() 方法接收内容
简单示例
创建一个 Human 类
package cn.bcrab.agent;
import java.io.Serializable;
public class Human implements Serializable {
String name;
int age;
String gender;
Human(String name, int age, String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public String toString(){
return "name: "+ name + "age: " + age + "gender: " + gender;
}
}
发送类 Sender.java
package cn.bcrab.agent;
import jade.core.AID;
import jade.core.Agent;
import jade.lang.acl.ACLMessage;
import java.io.IOException;
public class Sender extends Agent {
@Override
protected void setup() {
try {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.setContent("hello world");
AID a = new AID("Receiver", AID.ISLOCALNAME);
msg.addReceiver(a);
Human human = new Human("Bruce", 18, "Man");
msg.setContentObject(human);
msg.setLanguage("JavaSerialization");
send(msg);
} catch (IOException e) {
e.printStackTrace();
}
doDelete();
}
}
接收类 Receiver.java
package cn.bcrab.agent;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;
public class Receiver extends Agent{
@Override
protected void setup() {
addBehaviour(new CyclicBehaviour(this) {
@Override
public void action() {
try {
ACLMessage msg = blockingReceive();
System.out.println(getLocalName() + " receive msg :" + msg);
if ("JavaSerialization".equals(msg.getLanguage())){
Human human = (Human)msg.getContentObject();
System.out.println(getLocalName() + " 获取Java对象");
System.out.println(human.getClass().getName());
System.out.println(human.toString());
}
}catch (UnreadableException e) {
System.err.println(getLocalName() + " catched exception " + e.getMessage());
}
block();
}
});
}
}
先启动 Receiver, 再启动Sender。
运行结果:
Receiver receive msg :(INFORM
:sender ( agent-identifier :name a@Platform :addresses (sequence http://DESKTOP-KQ727CJ:7778/acc ))
:receiver (set ( agent-identifier :name Receiver@Platform ) )
:X-JADE-Encoding Base64
:content "rO0ABXNyABRjbi5iY3JhYi5hZ2VudC5IdW1hbuz3L9Sc9EeXAgADSQADYWdlTAAGZ2VuZGVydAASTGphdmEvbGFuZy9TdHJpbmc7TAAEbmFtZXEAfgABeHAAAAASdAADTWFudAAFQnJ1Y2U="
:language JavaSerialization )
Receiver 获取Java对象
cn.bcrab.agent.Human
name: Bruceage: 18gender: Man
相关代码
https://gitee.com/2010jing/JADE-tutorial/tree/tutorial06/
Reference
网友评论