Client.java 2.47 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 62 63
package bidirectional;

import com.example.grpc.BidirectionalServiceGrpc.*;
import com.example.grpc.BidirectionalServiceGrpc;
import com.example.grpc.BidirectionalServiceOuterClass.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


public class Client {
    public final static String IP = "localhost";
    public final static int PORT = 8888;

    public static void main(String[] args) throws IOException {
        //Opening a connection with server
        final ManagedChannel channel = ManagedChannelBuilder.forTarget(IP+":"+PORT).usePlaintext().build();

        //Creating the asynchronous stub
        BidirectionalServiceStub stub = BidirectionalServiceGrpc.newStub(channel);

        //The stub returns a stream to communicate with the server.
        //The argument is the stream of messages which are transmitted by the server.
        StreamObserver<ClientRequest> serverStream = stub.bidirectional(new StreamObserver<ServerResponse>() {
            //Remember: all the methods here are CALLBACKS which are handled in an asynchronous manner.

            //We define what to do when a message from the server arrives (just print the message)
            public void onNext(ServerResponse serverResponse) {
                System.out.println("[FROM SERVER] " + serverResponse.getStringResponse());
            }

            public void onError(Throwable throwable) {
            }

            public void onCompleted() {
            }
        });

        String msg = "First request from the client";
        System.out.println("Sending the message '" + msg + "' to the server...");
        serverStream.onNext(ClientRequest.newBuilder().setStringRequest(msg).build());

        msg = "Second request from the client";
        System.out.println("Sending the message '" + msg + "' to the server...");
        serverStream.onNext(ClientRequest.newBuilder().setStringRequest(msg).build());

        msg = "Third request from the client";
        System.out.println("Sending the message '" + msg + "' to the server...");
        serverStream.onNext(ClientRequest.newBuilder().setStringRequest(msg).build());



        try {
            //You need this. otherwise the method will terminate before that answers from the server are received
            channel.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}