Client.java 2.47 KB
Newer Older
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();
        }
    }

}