Amf0Util.java
1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.genersoft.iot.vmp.jtt1078.rtmp;
import io.netty.buffer.ByteBuf;
import java.util.Map;
/**
* AMF0 编码工具类
*/
public class Amf0Util {
// AMF0 Markers
public static final byte NUMBER = 0x00;
public static final byte BOOLEAN = 0x01;
public static final byte STRING = 0x02;
public static final byte OBJECT = 0x03;
public static final byte NULL = 0x05;
public static final byte ECMA_ARRAY = 0x08;
public static final byte OBJECT_END = 0x09;
public static void writeString(ByteBuf out, String str) {
out.writeByte(STRING);
writeStringBare(out, str);
}
// 不带 Marker 的字符串(用于 Object 的 Key)
public static void writeStringBare(ByteBuf out, String str) {
if (str == null) str = "";
byte[] bytes = str.getBytes();
out.writeShort(bytes.length);
out.writeBytes(bytes);
}
public static void writeNumber(ByteBuf out, double num) {
out.writeByte(NUMBER);
out.writeLong(Double.doubleToLongBits(num));
}
public static void writeBoolean(ByteBuf out, boolean val) {
out.writeByte(BOOLEAN);
out.writeByte(val ? 1 : 0);
}
public static void writeNull(ByteBuf out) {
out.writeByte(NULL);
}
public static void writeObject(ByteBuf out, Map<String, Object> props) {
out.writeByte(OBJECT);
if (props != null) {
for (Map.Entry<String, Object> entry : props.entrySet()) {
writeStringBare(out, entry.getKey());
Object val = entry.getValue();
if (val instanceof String) writeString(out, (String) val);
else if (val instanceof Number) writeNumber(out, ((Number) val).doubleValue());
else if (val instanceof Boolean) writeBoolean(out, (Boolean) val);
else writeNull(out);
}
}
// Object End Marker (00 00 09)
out.writeMedium(0x000009);
}
}