我有一個套接字服務器,它不斷監聽傳入的請求。收到的數據將以二進制字節數組的形式出現。數據格式是這樣的。 2321902321221200AA解析通過TCP套接字服務器接收的java中的二進制數據
- 鑑於字節數據開始
- 位是 版本
- 4個比特是數據返回類型
- 字節是產品代碼
- 字節數據長度
問題是,如何解析數據並分離參數。
在此先感謝!
我有一個套接字服務器,它不斷監聽傳入的請求。收到的數據將以二進制字節數組的形式出現。數據格式是這樣的。 2321902321221200AA解析通過TCP套接字服務器接收的java中的二進制數據
問題是,如何解析數據並分離參數。
在此先感謝!
try {
char [] cbuf = new char[16];
char databegin = cbuf[0];
char [] version = Arrays.copyOfRange(cbuf, 1, 6)
char [] product_typep = Arrays.copyOfRange(cbuf, 7, 12)
char []data_lendth = Arrays.copyOfRange(cbuf, 13, 15)
} catch(Error e){
System.out.println(e);
}
byte [] data = receiveData();
int dataBegin = data [0]; // Once field is 1-byte, it is simple!
int version = data [1] & 0x0F; // Use shift (>>>) and binary "and" (&)
int returnCode = // to extract value of fields that are
(data [1] >>> 4) & 0x0F; // smaller than one byte
byte [] productCode = // Copy fixed-size portions of data
new byte [] { // into separate arrays using hardcode
data [2], data [3], // (as here), or System.arrayCopy
data [4], data [5], // in case field occupies quite
data [6]}; // a many bytes.
int dataLength = // Use shift (<<) binary or (|) to
(data [7] & 0xFF) | // Combine several bytes into one integer
((data [8] & 0xFF) << 8); // We assume little-endian encoding here
嘗試java.io.DataInputStream中:
DataInputStream dis = new DataInputStream(in);
byte b = dis.readByte();
int version = (b >> 4) & 0xF;
int returnType = b & 0xF;
byte[] productCode = new byte[5];
dis.readFully(productCode);
int len = dis.readShort() & 0xFFFF;
我就得到了包讀者的一些王:
class Record {
.....
Record static fromBytes(byte[] bytes) {
// here use ByteBuffer or DataInputStream to extract filds
......
}
}
Record readNextRecord(InputStream in) {
int len = in.read() && 0xFF;
byte[] data = new byte[len];
in.read(data);
return Record.fromBytes(data)
}
{
InputStream in = ....;
Record r readNextRecord(in);
process (r);
}
當然你需要添加錯誤處理。一般來說,對於應該運行可靠的東西,我會建議使用像Grizzly或Netty這樣的NIO框架。
如果使用java binary block parser那麼代碼看起來像
class Parsed {
@Bin byte begin;
@Bin(type = BinType.BIT) int version;
@Bin(type = BinType.BIT) int returnType;
@Bin byte [] productCode;
@Bin(type = BinType.USHORT) int dataLength;
}
final Parsed parsed = JBBPParser.prepare("byte begin; bit:4 version; bit:4 returnType; byte [5] productCode; ushort dataLength;")
.parse(new byte[]{0x23,0x21,(byte)0x90,0x23,0x21,0x22,0x12,0x00,(byte)0xAA})
.mapTo(Parsed.class);
assertEquals(0x23, parsed.begin);
assertEquals(0x01, parsed.version);
assertEquals(0x02, parsed.returnType);
assertArrayEquals(new byte[]{(byte)0x90,0x23,0x21,0x22,0x12}, parsed.productCode);
assertEquals(0x00AA,parsed.dataLength);
ByteArrayOutputStream不回答這個問題,它只是移動的問題。 – EJP 2013-02-10 09:00:45