import java.util.*;class Packet{
private byte[] buf=null;
/**
* 将int转为低字节在前,高字节在后的byte数组
*/
private static byte[] intToLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
/*
*将String转为int+byte数组
*/
private static byte[] stringTo(String str){
byte[] temp=null;
byte[] tp=null;
temp=new byte[4+str.length()];
tp=intToLH(str.length());
System.arraycopy(tp,0,temp,0,4);
System.arraycopy(str.getBytes(),0,temp,4,str.length());
return temp;
}
public Packet(String str1,String str2){
byte[] temp=null;
buf=new byte[str1.length()+str2.length()+8];
temp=stringTo(str1);
System.arraycopy(temp,0,buf,0,str1.length()+4);
temp=stringTo(str2);
System.arraycopy(temp,0,buf,str1.length()+4,str1.length()+str2.length()+8);
}
/*
*返回要发送的数组
*/
public byte[] getBuf(){
return buf;
}
public static void main(String[] args) {
System.out.println(new Packet("zaole","bearerzi").getBuf());
}
}
private byte[] buf=null;
/**
* 将int转为低字节在前,高字节在后的byte数组
*/
private static byte[] intToLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
/*
*将String转为int+byte数组
*/
private static byte[] stringTo(String str){
byte[] temp=null;
byte[] tp=null;
temp=new byte[4+str.length()];
tp=intToLH(str.length());
System.arraycopy(tp,0,temp,0,4);
System.arraycopy(str.getBytes(),0,temp,4,str.length());
return temp;
}
public Packet(String str1,String str2){
byte[] temp=null;
buf=new byte[str1.length()+str2.length()+8];
temp=stringTo(str1);
System.arraycopy(temp,0,buf,0,str1.length()+4);
temp=stringTo(str2);
System.arraycopy(temp,0,buf,str1.length()+4,str1.length()+str2.length()+8);
}
/*
*返回要发送的数组
*/
public byte[] getBuf(){
return buf;
}
public static void main(String[] args) {
System.out.println(new Packet("zaole","bearerzi").getBuf());
}
}
如果两边都是Java,可以用Object Stream做。
发送方开ObjectOutputStream,writeObject(data)发出数据,
接收方开ObjectInputStream,readObject接收数据。