SumServiceImpl.java 2.38 KB
Newer Older
Michele Fiori's avatar
Michele Fiori committed
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
package SumServiceGRPC;

import io.grpc.stub.StreamObserver;

public class SumServiceImpl extends SumServiceGrpc.SumServiceImplBase {

    @Override
    public void simpleSum(SumServiceOuterClass.SimpleSumRequest request, StreamObserver<SumServiceOuterClass.SumServiceResponse> responseObserver){
        System.out.println(request);

        SumServiceOuterClass.SumServiceResponse response = SumServiceOuterClass.SumServiceResponse.newBuilder()
                                                                .setRes(request.getA() + request.getB())
                                                                .build();

        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public void repeatedSum(SumServiceOuterClass.RepeatedSumRequest request, StreamObserver<SumServiceOuterClass.SumServiceResponse> responseObserver){
        System.out.println(request);

        for(int i = 1; i<request.getT()+1; i++) {
            SumServiceOuterClass.SumServiceResponse response = SumServiceOuterClass.SumServiceResponse.newBuilder()
                    .setRes(request.getN() * i)
                    .build();

            responseObserver.onNext(response);
        }

        responseObserver.onCompleted();
    }

    @Override
    public StreamObserver<SumServiceOuterClass.SimpleSumRequest> streamSum(final StreamObserver<SumServiceOuterClass.SumServiceResponse> responseObserver){
        //it returns the stream that will be used by the clients to send messages.
        //the client will write on this stream
        return new StreamObserver<SumServiceOuterClass.SimpleSumRequest>() {
            //receiving a message from the client
            public void onNext(SumServiceOuterClass.SimpleSumRequest clientMessage) {
                System.out.println(clientMessage);

                responseObserver.onNext(SumServiceOuterClass.SumServiceResponse.newBuilder()
                        .setRes(clientMessage.getA() + clientMessage.getB())
                        .build());
            }

            //if there is an error (client abruptly disconnect) we remove the client.
            public void onError(Throwable throwable) {

            }

            //if the client explicitly terminated, we remove it from the hashset.
            public void onCompleted() {

            }
        };
    }

}