package com.j2medev.chapter5;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class Message {
//定义type的常量
public static final int ALL_FRAMES = -1;
public static final int SIGNUP = 0;
public static final int SIGNUP_ACK = 1;
public static final int CLIENT_STATUS = 2;
public static final int SERVER_STATUS = 3;
public static final int ERROR = 4;
public static final int SIGNOFF = 5;
private int type;//消息类型
private int size;//body的大小
private int[] body;//body的内容
public Message(int type) {
this.type = type;
this.size = 0;
}
public Message(int type, int data) {
this.type = type;
this.size = 1;
body = new int[] {
data
};
}
public Message(int type,int[] data){
this.type = type;
this.size = data.length;
this.body = data;
}
public int getType() {
return type;
}
public int getSize() {
return size;
}
public int[] getBody() {
return body;
}
//发送数据
public void send(DataOutputStream out) throws IOException {
out.writeInt(type);
out.writeInt(size);
for (int i = 0; i < size; i++) {
out.writeInt(body[i]);
}
out.flush();
}
//解析收到的数据
public static Message read(DataInputStream in)
throws IOException {
Message msg = new Message(in.readInt());
msg.size = in.readInt();
msg.body = new int[msg.getSize()];
for (int i = 0; i < msg.getSize(); i++) {
msg.body[i] = in.readInt();
}
return msg;
}
}