相信大家都看过许多有关java对象序列化的文章了,有关这个我也就不说什么了。
进入正题,下面是一个用DatagramSocket实现在线发送对象的例子,先前做课程设计时找了一下,发现大部分都是用Socket实现的,因此给出自己的程序供参考。
(1)首先是需要发送的类结构
import java.io.Serializable;
public class Protocal implements Serializable
{
public int type; //类型
public int seq; //序列号
public int acc; //确认号
public int length;
public int SYN;
public int ACK;
public int FINT;
public int xWindow; //窗口大小
public String date;
public Protocal(int type,int seq,int acc,int length,int SYN,int ACK,int FINT,int xWindow,String date)
{
this.type=type;
this.seq=seq;
this.acc=acc;
this.length=length;
this.SYN=SYN;
this.FINT=FINT;
this.ACK=ACK;
this.xWindow=xWindow;
this.date=date;
}
public Protocal()
{
}
}
注意的地方就是要实现Serializable接口
(2)对象发送函数
public void sendMessage(InetAddress receiveHost,int receivePort,Protocal message) throws IOException
{
try
{
ByteArrayOutputStream bout=new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(message); //序列化对象
oout.flush();
byte[] sendBuff=bout.toByteArray(); //转化为字节数组
DatagramPacket datagram=new DatagramPacket(sendBuff,sendBuff.length,receiveHost,receivePort);
this.send(datagram); //通过DatagramPacket发送对象
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
要点是要将序列化对象转化为字节流进行发送。
(3)
public Protocal receiveMessage() throws IOException
{
byte[] receiveBuff=new byte[MAX_LEN];
DatagramPacket datagram=new DatagramPacket(receiveBuff,MAX_LEN);
this.receive(datagram); //接收对象字节流
Protocal message=new Protocal();
try
{
ByteArrayInputStream bint=new ByteArrayInputStream(receiveBuff);
ObjectInputStream oint=new ObjectInputStream(bint);
message=(Protocal)oint.readObject(); //反序列化,恢复对象
catch(Exception ex)
{
ex.printStackTrace();
}
return message;
}