我正在开发一个聊天应用程序,使用GRPC,其中服务器接收来自客户端的信息并将其发送回连接到它的所有客户端。为此,我使用了Saturnism的chat-example作为参考。我已经复制了代码,代码编译并运行,但是服务器似乎从未收到来自客户端的任何请求。
我的问题是:
我的问题是:
- 是否有一种方法可以在GRPC中启用服务器端和客户端端详细日志记录,以查看进出的请求和响应以及可能失败的原因?
- 我正在使用以下代码进行服务器和客户端。下面的代码可能缺少/错误,导致客户端和服务器之间没有通信。
WingokuServer.java
public class WingokuServer {
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8091)
.intercept(recordRequestHeadersInterceptor())
.addService(new WingokuServiceImpl())
.build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
WingokuServerSideServiceImplementation:
public class WingokuServiceImpl extends WingokuServiceGrpc.WingokuServiceImplBase {
private static Set<StreamObserver<Response>> observers =
Collections.newSetFromMap(new ConcurrentHashMap<>());
public WingokuServiceImpl() {
System.out.println("WingokuServiceImp");
}
@Override
public StreamObserver<Request> messages(StreamObserver<Response> responseObserver) {
System.out.println("messages");
observers.add(responseObserver);
return new StreamObserver<Request>() {
@Override
public void onNext(Request request) {
System.out.println("Server onNext: ");
System.out.println("request from client is: "+ request.getRequestMessage());
Response response = Response.newBuilder().setResponseMessage("new Message From server at time: "+ System.nanoTime()).build();
for (StreamObserver<Response> observer : observers) {
observer.onNext(response);
}
}
@Override
public void onError(Throwable throwable) {
System.out.println("Server onError: ");
throwable.printStackTrace();
}
@Override
public void onCompleted() {
observers.remove(responseObserver);
System.out.println("Server onCompleted ");
}
};
}
}
Wingoku客户端:
public class WingokuClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8091).usePlaintext(true).build();
WingokuServiceGrpc.WingokuServiceStub asyncStub = WingokuServiceGrpc.newStub(channel);
StreamObserver<Request> requestStreamObserver = asyncStub.messages(new StreamObserver<Response>() {
@Override
public void onNext(Response response) {
System.out.println("Client onNext");
System.out.println("REsponse from server is: "+ response.getResponseMessage());
}
@Override
public void onError(Throwable throwable) {
System.out.println("Client onError");
throwable.printStackTrace();
}
@Override
public void onCompleted() {
System.out.println("Client OnComplete");
}
});
requestStreamObserver.onNext(Request.newBuilder().setRequestMessage("Message From Client").build());
requestStreamObserver.onCompleted();
channel.shutdown();
System.out.println("exiting client");
}
}
编辑:
代码没有问题。它可以正常工作。我只需要在客户端的通道中添加awaitTermination,因为没有它,连接就会立即关闭,可能甚至在请求从客户端传输到网络之前就关闭了。这就是为什么服务器从未收到任何请求。
但是,我仍然有关于启用详细日志记录和/或在服务器端添加某种拦截器的问题尚未得到回答。因此,我期待着从这里的专家那里获得一些指导。