forked from decipherhub/MSM-grpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
82 lines (71 loc) · 1.92 KB
/
server.ts
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
import * as grpc from "@grpc/grpc-js";
import * as protoLoader from "@grpc/proto-loader";
import path from "path";
interface StreamRequest {
clientId: string;
}
interface ComputationData {
data: string;
}
// Define the path to your .proto file
const PROTO_PATH = path.resolve(__dirname, "computation.proto");
// Load the .proto file
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
// Assume your package is named "computation"
const computation = protoDescriptor.computation as any;
const server = new grpc.Server();
const sendComputationData: grpc.handleUnaryCall<any, any> = (
call,
callback
) => {
console.log(`Received computation data: ${call.request.data}`);
callback(null, { success: true });
};
const getComputationResult: grpc.handleUnaryCall<any, any> = (
call,
callback
) => {
console.log(`Received computation result: ${call.request.result}`);
callback(null, { success: true });
};
const streamComputationData: grpc.handleServerStreamingCall<
StreamRequest,
ComputationData
> = (call) => {
let count = 0;
const intervalId = setInterval(() => {
count++;
if (count > 10) {
// 예시로 10번 데이터를 보낸 후 종료
clearInterval(intervalId);
call.end();
return;
}
const data = { data: `Data ${count}` }; // 연산 데이터 생성
call.write(data);
}, 5000); // 5초 간격으로 데이터 보내기
};
server.addService(computation.ComputationService.service, {
sendComputationData,
getComputationResult,
streamComputationData,
});
server.bindAsync(
"0.0.0.0:50051",
grpc.ServerCredentials.createInsecure(),
(error, port) => {
if (error) {
console.error(error);
return;
}
server.start();
console.log(`Server running at http://0.0.0.0:${port}`);
}
);