• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import grpc from 'grpc';
2import { HelloReply } from './models/hello-reply';
3import { HelloRequest } from './models/hello-request';
4import { IGreeterServer, GreeterService } from './greeter_grpc';
5import { flatbuffers } from 'flatbuffers';
6
7class GreeterServer implements IGreeterServer {
8
9    SayHello(call: grpc.ServerUnaryCall<HelloRequest>, callback: grpc.sendUnaryData<HelloReply>): void {
10        console.log(`SayHello ${call.request.name()}`);
11        const builder = new flatbuffers.Builder();
12        const offset = builder.createString(`welcome ${call.request.name()}`);
13        const root = HelloReply.createHelloReply(builder, offset);
14        builder.finish(root);
15        callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())));
16    }
17
18    async SayManyHellos(call: grpc.ServerWritableStream<HelloRequest>): Promise<void> {
19        const name = call.request.name();
20        console.log(`${call.request.name()} saying hi in different langagues`);
21        ['Hi', 'Hallo', 'Ciao'].forEach(element => {
22            const builder = new flatbuffers.Builder();
23            const offset = builder.createString(`${element} ${name}`);
24            const root = HelloReply.createHelloReply(builder, offset);
25            builder.finish(root);
26            call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())))
27        });
28        call.end();
29    }
30}
31
32function serve(): void {
33    const PORT = 3000;
34    const server = new grpc.Server();
35    server.addService<IGreeterServer>(GreeterService, new GreeterServer());
36    console.log(`Listening on ${PORT}`);
37    server.bind(`localhost:${PORT}`, grpc.ServerCredentials.createInsecure());
38    server.start();
39}
40
41serve();