Repository navigation
Expand file tree
/
Copy pathFuncServer.java
More file actions
391 lines (349 loc) · 16.7 KB
/
Copy pathFuncServer.java
File metadata and controls
391 lines (349 loc) · 16.7 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package demo;
import com.apihub.*;
import com.sun.jna.Pointer;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
/**
* FuncServer – 功能丰富的服务端,注册 13 个 API。
* 包含 SHA3-256 纯 Java 实现(自包含,无外部依赖)。
* 支持 IPC 和 TCP,同时自连以允许本地环回。
*
* <p><b>Cross‑language string protocol (2026-08-21):</b> All string
* I/O now uses {@link DataHandle#writeStringNullTerminated(String)}
* and {@link DataHandle#readStringNullTerminated()}, which are
* fully compatible with the Pascal {@code API_WriteString} /
* {@code API_ReadString} contract (UTF‑8 + NUL terminator).</p>
*/
public class FuncServer {
// ============================================================
// 1. 业务逻辑(纯函数,无序列化)
// ============================================================
private static int add(int a, int b) { return a + b; }
private static int subtract(int a, int b) { return a - b; }
private static int multiply(int a, int b) { return a * b; }
private static double divide(int a, int b) { return b == 0 ? 0.0 : (double) a / b; }
private static String toUpper(String s) { return s.toUpperCase(); }
private static String toLower(String s) { return s.toLowerCase(); }
private static String reverse(String s) { return new StringBuilder(s).reverse().toString(); }
private static String getTime() { return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); }
private static int getRandom(int min, int max) { return new Random().nextInt(max - min + 1) + min; }
private static String echo(String s) { return s; }
private static int sumArray(int[] arr) { int sum = 0; for (int v : arr) sum += v; return sum; }
private static String concatStrings(String[] arr) { return String.join(" ", arr); }
// ============================================================
// 2. SHA3-256 纯 Java 实现(Keccak-f[1600])
// ============================================================
private static class Sha3 {
private static final int ROUNDS = 24;
private static final long[] ROUND_CONSTANTS = {
0x0000000000000001L, 0x0000000000008082L, 0x800000000000808aL,
0x8000000080008000L, 0x000000000000808bL, 0x0000000080000001L,
0x8000000080008081L, 0x8000000000008009L, 0x000000000000008aL,
0x0000000000000088L, 0x0000000080008009L, 0x000000008000000aL,
0x000000008000808bL, 0x800000000000008bL, 0x8000000000008089L,
0x8000000000008003L, 0x8000000000008002L, 0x8000000000000080L,
0x000000000000800aL, 0x800000008000000aL, 0x8000000080008081L,
0x8000000000008080L, 0x0000000080000001L, 0x8000000080008008L
};
private static final int[] RHO_OFFSETS = {
0, 1, 62, 28, 27, 36, 44, 6, 55, 20,
3, 10, 43, 25, 39, 41, 45, 15, 21, 8,
18, 2, 61, 56, 14
};
private static long rotl64(long x, int n) {
return (x << n) | (x >>> (64 - n));
}
private static void keccakF1600(long[] state) {
for (int round = 0; round < ROUNDS; round++) {
// Theta
long[] C = new long[5];
long[] D = new long[5];
for (int x = 0; x < 5; x++)
C[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20];
for (int x = 0; x < 5; x++)
D[x] = C[(x + 4) % 5] ^ rotl64(C[(x + 1) % 5], 1);
for (int x = 0; x < 5; x++)
for (int y = 0; y < 5; y++)
state[x + 5 * y] ^= D[x];
// Rho and Pi
long current = state[1];
for (int t = 0; t < 24; t++) {
int x, y;
int idx = t + 1;
if (idx == 1) { x = 0; y = 1; }
else if (idx == 2) { x = 1; y = 0; }
else if (idx == 3) { x = 1; y = 1; }
else if (idx == 4) { x = 0; y = 2; }
else if (idx == 5) { x = 2; y = 0; }
else if (idx == 6) { x = 2; y = 1; }
else if (idx == 7) { x = 1; y = 2; }
else if (idx == 8) { x = 2; y = 2; }
else if (idx == 9) { x = 0; y = 3; }
else if (idx == 10) { x = 3; y = 0; }
else if (idx == 11) { x = 3; y = 1; }
else if (idx == 12) { x = 1; y = 3; }
else if (idx == 13) { x = 3; y = 2; }
else if (idx == 14) { x = 2; y = 3; }
else if (idx == 15) { x = 3; y = 3; }
else if (idx == 16) { x = 0; y = 4; }
else if (idx == 17) { x = 4; y = 0; }
else if (idx == 18) { x = 4; y = 1; }
else if (idx == 19) { x = 1; y = 4; }
else if (idx == 20) { x = 4; y = 2; }
else if (idx == 21) { x = 2; y = 4; }
else if (idx == 22) { x = 4; y = 3; }
else if (idx == 23) { x = 3; y = 4; }
else if (idx == 24) { x = 4; y = 4; }
else { x = 0; y = 0; }
long temp = state[x + 5 * y];
state[x + 5 * y] = rotl64(current, RHO_OFFSETS[t]);
current = temp;
}
// Chi
for (int y = 0; y < 5; y++) {
long[] temp = new long[5];
for (int x = 0; x < 5; x++)
temp[x] = state[x + 5 * y];
for (int x = 0; x < 5; x++)
state[x + 5 * y] = temp[x] ^ ((~temp[(x + 1) % 5]) & temp[(x + 2) % 5]);
}
// Iota
state[0] ^= ROUND_CONSTANTS[round];
}
}
public static byte[] hash(byte[] input) {
long[] state = new long[25];
int rate = 136; // 1600 - 2*256 = 1088 bits = 136 bytes
int offset = 0;
int len = input.length;
int pos = 0;
while (len > 0) {
int chunk = Math.min(len, rate - offset);
for (int i = 0; i < chunk; i++) {
int idx = (offset + i) >>> 3;
int shift = 8 * ((offset + i) & 7);
state[idx] ^= (long) (input[pos + i] & 0xFF) << shift;
}
offset += chunk;
pos += chunk;
len -= chunk;
if (offset == rate) {
keccakF1600(state);
offset = 0;
}
}
state[offset >>> 3] ^= 0x06L << (8 * (offset & 7));
state[(rate - 1) >>> 3] ^= 0x80L << (8 * ((rate - 1) & 7));
keccakF1600(state);
byte[] hash = new byte[32];
for (int i = 0; i < 32; i++) {
hash[i] = (byte) (state[i >>> 3] >>> (8 * (i & 7)));
}
return hash;
}
public static String hashHex(String input) {
byte[] hash = hash(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) sb.append(String.format("%02x", b & 0xFF));
return sb.toString();
}
}
// ============================================================
// 3. API 回调函数(从 DataHnd 读写)
// All string I/O now uses NUL‑terminated format for cross‑language compatibility.
// ============================================================
private static void addCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
int a = in.readInt();
int b = in.readInt();
out.writeInt(add(a, b));
} catch (Exception e) {
System.err.println("addCallback error: " + e.getMessage());
}
}
private static void subtractCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
int a = in.readInt();
int b = in.readInt();
out.writeInt(subtract(a, b));
} catch (Exception e) {
System.err.println("subtractCallback error: " + e.getMessage());
}
}
private static void multiplyCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
int a = in.readInt();
int b = in.readInt();
out.writeInt(multiply(a, b));
} catch (Exception e) {
System.err.println("multiplyCallback error: " + e.getMessage());
}
}
private static void divideCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
int a = in.readInt();
int b = in.readInt();
out.writeDouble(divide(a, b));
} catch (Exception e) {
System.err.println("divideCallback error: " + e.getMessage());
}
}
private static void toUpperCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
String s = in.readStringNullTerminated();
out.writeStringNullTerminated(toUpper(s));
} catch (Exception e) {
System.err.println("toUpperCallback error: " + e.getMessage());
}
}
private static void toLowerCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
String s = in.readStringNullTerminated();
out.writeStringNullTerminated(toLower(s));
} catch (Exception e) {
System.err.println("toLowerCallback error: " + e.getMessage());
}
}
private static void reverseCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
String s = in.readStringNullTerminated();
out.writeStringNullTerminated(reverse(s));
} catch (Exception e) {
System.err.println("reverseCallback error: " + e.getMessage());
}
}
private static void getTimeCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle out = DataHandle.wrapOutput(output);
out.writeStringNullTerminated(getTime());
} catch (Exception e) {
System.err.println("getTimeCallback error: " + e.getMessage());
}
}
private static void getRandomCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
int min = in.readInt();
int max = in.readInt();
out.writeInt(getRandom(min, max));
} catch (Exception e) {
System.err.println("getRandomCallback error: " + e.getMessage());
}
}
private static void echoCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
String s = in.readStringNullTerminated();
out.writeStringNullTerminated(echo(s));
} catch (Exception e) {
System.err.println("echoCallback error: " + e.getMessage());
}
}
private static void sumArrayCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
// 数组格式:先读长度,再读每个元素
int len = in.readInt();
int[] arr = new int[len];
for (int i = 0; i < len; i++) arr[i] = in.readInt();
out.writeInt(sumArray(arr));
} catch (Exception e) {
System.err.println("sumArrayCallback error: " + e.getMessage());
}
}
private static void concatStringsCallback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
int len = in.readInt();
String[] arr = new String[len];
for (int i = 0; i < len; i++) {
arr[i] = in.readStringNullTerminated();
}
out.writeStringNullTerminated(concatStrings(arr));
} catch (Exception e) {
System.err.println("concatStringsCallback error: " + e.getMessage());
}
}
private static void sha3Callback(Pointer trigger, Pointer input, Pointer output) {
try {
DataHandle in = DataHandle.wrapInput(input);
DataHandle out = DataHandle.wrapOutput(output);
String s = in.readStringNullTerminated();
out.writeStringNullTerminated(Sha3.hashHex(s));
} catch (Exception e) {
System.err.println("sha3Callback error: " + e.getMessage());
}
}
// ============================================================
// 4. 主程序
// ============================================================
public static void main(String[] args) {
System.out.println("=== Java FuncService (13 APIs) ===");
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutdown hook triggered.");
ApiHub.exitMainThread();
ApiHub.shutdown();
}));
try (AppHandle app = new AppHandle("FuncService", "Functional service with 13 APIs")) {
app.registerCall("add", "Add two integers", FuncServer::addCallback);
app.registerCall("subtract", "Subtract two integers", FuncServer::subtractCallback);
app.registerCall("multiply", "Multiply two integers", FuncServer::multiplyCallback);
app.registerCall("divide", "Divide two integers (returns double)", FuncServer::divideCallback);
app.registerCall("to_upper", "Convert string to uppercase", FuncServer::toUpperCallback);
app.registerCall("to_lower", "Convert string to lowercase", FuncServer::toLowerCallback);
app.registerCall("reverse", "Reverse a string", FuncServer::reverseCallback);
app.registerCall("get_time", "Get current time", FuncServer::getTimeCallback);
app.registerCall("get_random", "Get random integer in [min, max]", FuncServer::getRandomCallback);
app.registerCall("echo", "Echo input string", FuncServer::echoCallback);
app.registerCall("sum_array", "Sum an array of integers", FuncServer::sumArrayCallback);
app.registerCall("concat_strings", "Concatenate strings with spaces", FuncServer::concatStringsCallback);
app.registerCall("sha3", "SHA3-256 hash (hex)", FuncServer::sha3Callback);
System.out.println("Registered 13 APIs.");
ApiHub.resetPrepare();
ApiHub.prepareService("ipc:func_service", "ipc:func_service");
ApiHub.prepareService("0.0.0.0", "127.0.0.1:9899");
ApiHub.prepareClient("ipc:func_service", app);
ApiHub.prepareClient("127.0.0.1:9899", app);
if (!ApiHub.prepareDone()) {
System.err.println("Prepare failed. Please check console output for errors.");
return;
}
System.out.println("Service started on ipc:func_service and TCP 127.0.0.1:9899");
System.out.println("Press Ctrl+C to stop...");
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted, shutting down...");
Thread.currentThread().interrupt();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ApiHub.exitMainThread();
ApiHub.shutdown();
}
}
}