<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-core</artifactId>
<version>1.38.0</version>
</dependency>
</dependencies>
groovy
dependencies {
implementation 'io.grpc:grpc-core:1.38.0'
}
protobuf
syntax = "proto3";
message LoginRequest {
string username = 1;
string password = 2;
}
message LoginResponse {
bool success = 1;
string message = 2;
}
service AuthenticationService {
rpc login(LoginRequest) returns (LoginResponse);
}
shell
protoc -I=. --java_out=. Authentication.proto
import io.grpc.stub.StreamObserver;
public class AuthenticationServiceImpl extends AuthenticationServiceGrpc.AuthenticationServiceImplBase {
@Override
public void login(LoginRequest request, StreamObserver<LoginResponse> responseObserver) {
String username = request.getUsername();
String password = request.getPassword();
boolean success = authenticateUser(username, password);
String message = success ? "Authentication successful" : "Authentication failed";
LoginResponse response = LoginResponse.newBuilder()
.setSuccess(success)
.setMessage(message)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
private boolean authenticateUser(String username, String password) {
// ...
}
}
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class GRPCServer {
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8080)
.addService(new AuthenticationServiceImpl())
.build();
server.start();
System.out.println("Server started");
server.awaitTermination();
}
}
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class GRPCClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
.usePlaintext()
.build();
AuthenticationServiceGrpc.AuthenticationServiceBlockingStub stub = AuthenticationServiceGrpc.newBlockingStub(channel);
LoginRequest request = LoginRequest.newBuilder()
.setUsername("johnDoe")
.setPassword("password123")
.build();
LoginResponse response = stub.login(request);
if (response.getSuccess()) {
System.out.println("Authentication successful");
} else {
System.out.println("Authentication failed: " + response.getMessage());
}
channel.shutdown();
}
}