-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathclient.ts
100 lines (90 loc) · 2.46 KB
/
client.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import * as grpc from '@grpc/grpc-js';
import * as protoLoader from '@grpc/proto-loader';
import { ProtoGrpcType } from './proto/example';
import { ServerMessage } from './proto/example_package/ServerMessage';
const host = '0.0.0.0:9090';
const packageDefinition = protoLoader.loadSync('./proto/example.proto', {
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const proto = grpc.loadPackageDefinition(
packageDefinition
) as unknown as ProtoGrpcType;
const client = new proto.example_package.Example(
host,
grpc.credentials.createInsecure()
);
const deadline = new Date();
deadline.setSeconds(deadline.getSeconds() + 5);
client.waitForReady(deadline, (error?: Error) => {
if (error) {
console.log(`Client connect error: ${error.message}`);
} else {
onClientReady();
}
});
function onClientReady() {
switch (process.argv[process.argv.length - 1]) {
case '--unary':
doUnaryCall();
break;
case '--server-streaming':
doServerStreamingCall();
break;
case '--client-streaming':
doClientStreamingCall();
break;
case '--bidi-streaming':
doBidirectionalStreamingCall();
break;
default:
throw new Error('Example not specified');
}
}
function doUnaryCall() {
client.unaryCall(
{
clientMessage: 'Message from client',
},
(error?: grpc.ServiceError | null, serverMessage?: ServerMessage) => {
if (error) {
console.error(error.message);
} else if (serverMessage) {
console.log(
`(client) Got server message: ${serverMessage.serverMessage}`
);
}
}
);
}
function doServerStreamingCall() {
const stream = client.serverStreamingCall({
clientMessage: 'Message from client',
});
stream.on('data', (serverMessage: ServerMessage) => {
console.log(`(client) Got server message: ${serverMessage.serverMessage}`);
});
}
function doClientStreamingCall() {
const stream = client.clientStreamingCall((error?: grpc.ServiceError | null) => {
if (error) {
console.error(error.message);
}
});
stream.write({
clientMessage: 'Message from client',
});
}
function doBidirectionalStreamingCall() {
const stream = client.bidirectionalStreamingCall();
// Server stream
stream.on('data', (serverMessage: ServerMessage) => {
console.log(`(client) Got server message: ${serverMessage.serverMessage}`);
});
// Client stream
stream.write({
clientMessage: 'Message from client',
});
}