| 52 | |
| 53 | // 请求包结构 |
| 54 | public static class Request { |
| 55 | private byte type; // 1字节类型 |
| 56 | private int length; // 4字节长度 |
| 57 | private byte[] data; // 数据部分 |
| 58 | |
| 59 | public Request(byte type, byte[] data) { |
| 60 | this.type = type; |
| 61 | this.data = data; |
| 62 | this.length = data != null ? data.length : 0; |
| 63 | } |
| 64 | |
| 65 | // 编码请求包(带加密) |
| 66 | public byte[] encode() { |
| 67 | // 加密数据 |
| 68 | byte[] encryptedData = xorProcess(data); |
| 69 | |
| 70 | ByteBuffer buffer = ByteBuffer.allocate(MAGIC_PREFIX.length + 5 + length); |
| 71 | buffer.put(MAGIC_PREFIX); |
| 72 | buffer.put(type); |
| 73 | buffer.putInt(length); |
| 74 | if (encryptedData != null && length > 0) { |
| 75 | buffer.put(encryptedData); |
| 76 | } |
| 77 | return buffer.array(); |
| 78 | } |
| 79 | |
| 80 | // 解码请求包(带解密) |
| 81 | public static Request decode(byte[] rawData) { |
| 82 | if (!validate(rawData)) { |
| 83 | return null; |
| 84 | } |
| 85 | ByteBuffer buffer = ByteBuffer.wrap(rawData); |
| 86 | buffer.position(MAGIC_PREFIX.length); |
| 87 | byte type = buffer.get(); |
| 88 | int length = buffer.getInt(); |
| 89 | |
| 90 | // 读取并解密数据 |
| 91 | byte[] encryptedData = null; |
| 92 | if (length > 0) { |
| 93 | encryptedData = new byte[length]; |
| 94 | buffer.get(encryptedData); |
| 95 | encryptedData = xorProcess(encryptedData); |
| 96 | } |
| 97 | |
| 98 | return new Request(type, encryptedData); |
| 99 | } |
| 100 | |
| 101 | // 获取原始数据 |
| 102 | public byte[] getData() { |
| 103 | return data; |
| 104 | } |
| 105 | |
| 106 | // 获取解密后的字符串数据 |
| 107 | public String getDataAsString() { |
| 108 | return data != null ? new String(data, StandardCharsets.UTF_8) : ""; |
| 109 | } |
| 110 | } |
| 111 |
nothing calls this directly
no outgoing calls
no test coverage detected