移动开发中的通信架构(二) (三)

2014-11-24 02:43:03 · 作者: · 浏览: 3
;
out.write(tmp);
} catch (Exception ex1) {
}

}

public void writeStringArray(String[] v) {
for (int i = 0; i < v.length; i++) {
writeString(v[i]);
}
}

public void writeStrings(String[] v) {
writeLength(v.length);
for (int i = 0; i < v.length; i++) {
writeString(v[i]);
}
}

public void writeStrings2(String[][] v) {
writeLength(v.length);
for (int i = 0; i < v.length; i++) {
writeStrings(v[i]);
}
}

public void writeByteArray(byte[] v) {
writeLength(v.length);
for (int i = 0; i < v.length; i++) {
writeByte(v[i]);
}
}


public void writeByteArray2(byte[] v) {
for (int i = 0; i < v.length; i++) {
writeByte(v[i]);
}
}

public int getType() {
return commID;
}

/**
* 此方法可以实现对程序数据的加密
*/
public byte[] getBytes() {
if (!bTradeCipher) {
return bout.toByteArray();
} else {
byte[] data = bout.toByteArray();
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (data[i] ^ Globe.key[i % Globe.key.length]);
}
return data;
}
}

public void writeVector(Vector v) {
int num = v.size();
writeLength(num);
for (int i = 0; i < num; i++) {
writeString((String) v.elementAt(i));
}
}

public void cloese() {
try {
if (out != null) {
out.close();
}
if (bout != null) {
bout.close();
}
out = null;
bout = null;
} catch (IOException ex) {
}
}
}
package app.http;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import app.program.Globe;

/**
* 功能:把各种类型的数据,转换为字节数组。
*
* 属于工具类,为网络连接,本地数据存储提供从其他数据类型到字节数据类型的转换。
*
* 注意有些方法中包含了私有项目的网络协议,并没有删除。比如writeInts2中writeLength(v[0].length);
*/
public class StructRequest {
private ByteArrayOutputStream bout;

private DataOutputStream out;

private int commID;

private boolean bTradeCipher;

/**
* 默认为非加密通讯
*
* @param commID
* int
*/
public StructRequest(int commID) {
this();
this.commID = commID;
bTradeCipher = false;
}

/**
* @param commID
* int
* @param bTradeCipher
* boolean 表示是否需要加密
*/
public StructRequest(int commID, boolean bTradeCipher) {
this();
this.commID = commID;
this.bTradeCipher = bTradeCipher;
}

public StructRequest() {
bout = new ByteArrayOutputStream();
out = new DataOutputStream(bout);
}

public void writeLength(int v) {
writeShort(v);
}

public void writeBoolean(boolean v) {
try {
out.writeBoolean(v);
} catch (Exception ex) {
throw new RuntimeException();
}
}

public void writeBooleans(boolean[] v) {
writeLength(v.length);
for (int i = 0; i < v.length; i++) {
writeBoolean(v[i]);
}
}

public void writeBooleans2(boolean[][] v) {
writeLength(v.length);
if (v.length > 0) {
writeLength(v[0].length);
for (int i = 0; i < v.length; i++) {
for (int j = 0; j < v[0].length; j++) {
writeBoolean(v[i][j]);
}
}
}
}

public void writeByte(int v) {
try {
out.writeByte(v);
} catch (Exception ex) {
throw new RuntimeException();
}
}

public void writeBytes(int[] v) {
writeLength(v.length);
for (int i = 0; i < v.length; i++) {
writeByte(v[i]);
}
}