public byte[] getContent() {
return content;
}
public void sedIsTrade(boolean trade) {
this.bTrade = trade;
}
public boolean getIsTrade() {
return this.bTrade;
}
}
package app.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* 功能:
*
* 把需要发送的内容,再次经过私有协议封装,合并为一个Request对象,并且给这个对象一个和屏幕一致的ID,用于接收和解析数据
*
* 其他参照StructRequest
*/
public class Request {
private byte[] content = null;
private int screenId = 0;
private static final byte START_FLAG = (byte) '{';
private static final byte END_FLAG = (byte) '}';
private static final byte OTHER_FLAG = (byte) ':';
private boolean bTrade = false;
/**
* 单个通讯
*
* @param output
* StructOutput
*/
public Request(StructRequest output, int screeID) {
screenId = screeID;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(START_FLAG); // 标识符
out.write(output.getType() & 0xFF);
out.write((output.getType() >>> 8) & 0xFF);
out.write(0);
out.write(0);
out.write(output.getBytes().length & 0xFF);
out.write((output.getBytes().length >>> 8) & 0xFF);
out.write(output.getBytes());
out.write(END_FLAG); // 校验符
} catch (Exception ex) {
}
content = out.toByteArray();
try {
out.close();
} catch (IOException ex1) {
}
out = null;
}
public Request(int screeID) {
screenId = screeID;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(START_FLAG); // 标识符
out.write(0);
out.write(0);
out.write(0);
out.write(0);
out.write(0);
out.write(0);
out.write(END_FLAG); // 校验符
} catch (Exception ex) {
}
content = out.toByteArray();
try {
out.close();
} catch (IOException ex1) {
}
out = null;
}
/**
* 多个通讯
*
* @param output
* StructOutput[]
*/
public Request(StructRequest[] output, int screeID) {
screenId = screeID;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(START_FLAG); // 标识符
for (int i = 0; i < output.length; i++) {
out.write(output[i].getType() & 0xFF);
out.write((output[i].getType() >>> 8) & 0xFF);
out.write(0);
out.write(0);
out.write(output[i].getBytes().length & 0xFF);
out.write((output[i].getBytes().length >>> 8) & 0xFF);
out.write(output[i].getBytes());
if (i < output.length - 1) {
out.write(OTHER_FLAG);
}
}
out.write(END_FLAG); // 校验符
} catch (Exception ex) {
}
content = out.toByteArray();
try {
out.close();
} catch (IOException ex1) {
}
out = null;
}
public int getScreenId() {
return screenId;
}
public byte[] getContent() {
return content;
}
public void sedIsTrade(boolean trade) {
this.bTrade = trade;
}
public boolean getIsTrade() {
return this.bTrade;
}
}
补充说明:在通信的时候,有两种ID,首先是屏幕ID(本文第一段代码中的this.screenId),这个ID用来确定请求的屏幕,以便请求结束以后,由这个屏幕来解析响应。其次是请求ID(本文第一段代码中的GameConst.COMM_PRICECOUNT_DATA)。
为了便于读者理解,下面一段代码展示典型的响应解析方式:
view plaincopy to clipboardprint public void httpCompleted(Response resp) {
byte[] tmp = resp.getData(GameConst.COMM_DATA);//这里就根据请求ID来解析响应
if (tmp != null) {
}
}
public void httpCompleted(Response resp) {
byte[] tmp = resp.getData(GameConst.COMM_DATA);//这里就根据请求ID来解析响应
if (tmp != null) {
}
}
下一篇讲解请求的发送和响应的接收。
作者“冯小卫”