发布
社区首页 >问答首页 >使用基于Java的Grpc服务器和基于C++的客户端传输失败错误?

使用基于Java的Grpc服务器和基于C++的客户端传输失败错误?

提问于 2024-12-29 23:30:16
回答 0关注 0查看 27

服务端使用java语言,采用grpc框架,未使用springboot,c++20作为客户端去调用,报错如下

代码语言:txt
复制
12月 29, 2024 11:20:38 下午 io.grpc.netty.NettyServerTransport notifyTerminated
信息: Transport failed
java.net.SocketException: Connection reset
	at java.base/sun.nio.ch.SocketChannelImpl.throwConnectionReset(SocketChannelImpl.java:394)
	at java.base/sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:426)
	at io.netty.buffer.PooledByteBuf.setBytes(PooledByteBuf.java:247)
	at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1147)
	at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:347)
	at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:148)
	at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:700)
	at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:635)
	at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:552)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:514)
	at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1044)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
	at java.base/java.lang.Thread.run(Thread.java:833)

c++客户端的代码如下:

代码语言:txt
复制
#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>
#include "HelloWorld.grpc.pb.h"

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloResponse;
using helloworld::HelloWorld;

class HelloWorldClient {
public:
    HelloWorldClient(std::shared_ptr<Channel> channel) : stub_(HelloWorld::NewStub(channel)) {}

    std::string SayHello(const std::string& name) {
        HelloRequest request;
        request.set_name(name);

        ClientContext context;
        HelloResponse response;
        Status status = stub_->SayHello(&context, request, &response);
        if (status.ok()) {
            return response.message();
        } else {
            return "RPC failed";
        }
    }

private:
    std::unique_ptr<HelloWorld::Stub> stub_;
};

int main() {
    std::string server_address("127.0.0.1:9999");
    HelloWorldClient client(grpc::CreateChannel(server_address, grpc::InsecureChannelCredentials()));

    std::string user("Alice");
    std::string reply = client.SayHello(user);
    std::cout << "Received: " << reply << std::endl;

    return 0;
}

proto 文件如下

代码语言:txt
复制
syntax = "proto3";

option java_multiple_files = false;
option java_package = "com.example.grpc";
option java_outer_classname = "HelloWorldProto";

service HelloWorld {
  rpc SayHello (HelloRequest) returns (HelloResponse) {};
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}

服务端代码如下:

代码语言:txt
复制
public class HelloWorldServiceImpl extends HelloWorldGrpc.HelloWorldImplBase {
    @Override
    public void sayHello(HelloWorldProto.HelloRequest request, StreamObserver<HelloWorldProto.HelloResponse> responseObserver) {
        System.out.println("服务端接收到消息了,哈哈哈!");
        String message = "Hello, " + request.getName() + "!";
        HelloWorldProto.HelloResponse reply = HelloWorldProto.HelloResponse.newBuilder().setMessage(message).build();
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
}
代码语言:txt
复制
 public static void main(String[] args) throws InterruptedException, IOException {
        Server server = ServerBuilder.forPort(9999)
                .addService(new HelloWorldServiceImpl())
                .build();
        server.start();
        server.awaitTermination();
    }

java作为服务端,用java去写客户端调用是没问题的,c++作为客户端,用c++去写服务端调用是没问题的,但是跨语言之后,java作为服务端,c++作为客户端去调用就会产生文章开头的报错。

假如java作为客户端,c++作为服务端去调用,报错如下

代码语言:txt
复制
D:\software\openjdk17\jdk-17\bin\java.exe "-javaagent:D:\software\IntelliJ IDEA 2024.1.4\lib\idea_rt.jar=59204:D:\software\IntelliJ IDEA 2024.1.4\bin" -Dfile.encoding=UTF-8 -classpath D:\projects\grpc-server\target\classes;D:\mavenrepository\io\grpc\grpc-all\1.27.1\grpc-all-1.27.1.jar;D:\mavenrepository\io\grpc\grpc-api\1.27.1\grpc-api-1.27.1.jar;D:\mavenrepository\com\google\errorprone\error_prone_annotations\2.3.4\error_prone_annotations-2.3.4.jar;D:\mavenrepository\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;D:\mavenrepository\org\codehaus\mojo\animal-sniffer-annotations\1.18\animal-sniffer-annotations-1.18.jar;D:\mavenrepository\com\google\guava\guava\28.1-android\guava-28.1-android.jar;D:\mavenrepository\com\google\guava\failureaccess\1.0.1\failureaccess-1.0.1.jar;D:\mavenrepository\com\google\guava\listenablefuture\9999.0-empty-to-avoid-conflict-with-guava\listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar;D:\mavenrepository\org\checkerframework\checker-compat-qual\2.5.5\checker-compat-qual-2.5.5.jar;D:\mavenrepository\com\google\j2objc\j2objc-annotations\1.3\j2objc-annotations-1.3.jar;D:\mavenrepository\io\grpc\grpc-auth\1.27.1\grpc-auth-1.27.1.jar;D:\mavenrepository\com\google\auth\google-auth-library-credentials\0.19.0\google-auth-library-credentials-0.19.0.jar;D:\mavenrepository\io\grpc\grpc-core\1.27.1\grpc-core-1.27.1.jar;D:\mavenrepository\com\google\code\gson\gson\2.8.6\gson-2.8.6.jar;D:\mavenrepository\com\google\android\annotations\4.1.1.4\annotations-4.1.1.4.jar;D:\mavenrepository\io\perfmark\perfmark-api\0.19.0\perfmark-api-0.19.0.jar;D:\mavenrepository\io\grpc\grpc-context\1.27.1\grpc-context-1.27.1.jar;D:\mavenrepository\io\grpc\grpc-netty\1.27.1\grpc-netty-1.27.1.jar;D:\mavenrepository\io\netty\netty-codec-http2\4.1.42.Final\netty-codec-http2-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-common\4.1.42.Final\netty-common-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-buffer\4.1.42.Final\netty-buffer-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-transport\4.1.42.Final\netty-transport-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-resolver\4.1.42.Final\netty-resolver-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-codec\4.1.42.Final\netty-codec-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-handler\4.1.42.Final\netty-handler-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-codec-http\4.1.42.Final\netty-codec-http-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-handler-proxy\4.1.42.Final\netty-handler-proxy-4.1.42.Final.jar;D:\mavenrepository\io\netty\netty-codec-socks\4.1.42.Final\netty-codec-socks-4.1.42.Final.jar;D:\mavenrepository\io\grpc\grpc-okhttp\1.27.1\grpc-okhttp-1.27.1.jar;D:\mavenrepository\com\squareup\okio\okio\1.13.0\okio-1.13.0.jar;D:\mavenrepository\com\squareup\okhttp\okhttp\2.5.0\okhttp-2.5.0.jar;D:\mavenrepository\io\grpc\grpc-protobuf\1.27.1\grpc-protobuf-1.27.1.jar;D:\mavenrepository\com\google\protobuf\protobuf-java\3.11.0\protobuf-java-3.11.0.jar;D:\mavenrepository\com\google\api\grpc\proto-google-common-protos\1.17.0\proto-google-common-protos-1.17.0.jar;D:\mavenrepository\io\grpc\grpc-protobuf-lite\1.27.1\grpc-protobuf-lite-1.27.1.jar;D:\mavenrepository\io\grpc\grpc-stub\1.27.1\grpc-stub-1.27.1.jar;D:\mavenrepository\io\grpc\grpc-testing\1.27.1\grpc-testing-1.27.1.jar;D:\mavenrepository\io\opencensus\opencensus-api\0.24.0\opencensus-api-0.24.0.jar com.bugboy.GrpcClientCppServer
Exception in thread "main" java.util.concurrent.ExecutionException: io.grpc.StatusRuntimeException: UNIMPLEMENTED
	at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:396)
	at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:2073)
	at com.bugboy.GrpcClientCppServer.main(GrpcClientCppServer.java:47)
Caused by: io.grpc.StatusRuntimeException: UNIMPLEMENTED
	at io.grpc.Status.asRuntimeException(Status.java:533)
	at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:449)
	at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:426)
	at io.grpc.internal.ClientCallImpl.access$500(ClientCallImpl.java:66)
	at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:689)
	at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$900(ClientCallImpl.java:577)
	at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:751)
	at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:740)
	at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
	at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
	at java.base/java.lang.Thread.run(Thread.java:833)

Process finished with exit code 1

c++服务端代码

代码语言:txt
复制
#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>
#include "HelloWorld.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloResponse;
using helloworld::HelloWorld;

class HelloWorldImpl final : public HelloWorld::Service {
public:
    Status SayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloResponse* response) override
    {
        std::string prefix = "Hello, ";
        response->set_message(prefix + request->name());
        return Status::OK;
    }
};

void RunServer() {
    std::string server_address("0.0.0.0:50051");
    HelloWorldImpl service;

    ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);

    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;
    server->Wait();
}

int main() {
    RunServer();
    return 0;
}

java客户端代码

代码语言:txt
复制
 public static void main(String[] args) throws InterruptedException, ExecutionException {
        // forAddress(name, port)
        ManagedChannel channel =
                ManagedChannelBuilder.forAddress("localhost", 50051)
                        .usePlaintext()
                        .build();
        HelloWorldGrpc.HelloWorldStub stub = HelloWorldGrpc.newStub(channel);
        HelloWorldProto.HelloRequest helloRequest = HelloWorldProto.HelloRequest.newBuilder()
                .setName("FunTester newStub")
                .build();
        CompletableFuture<HelloWorldProto.HelloResponse> response = new CompletableFuture<>();
        stub.sayHello(helloRequest, new StreamObserver<HelloWorldProto.HelloResponse>() {
            @Override
            public void onNext(HelloWorldProto.HelloResponse helloResponse) {
                response.complete(helloResponse);
            }

            @Override
            public void onError(Throwable t) {
                response.completeExceptionally(t);
            }

            @Override
            public void onCompleted() {

            }
        });
        HelloWorldProto.HelloResponse rsp = response.get();
        System.out.println(rsp.getMessage());
        channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
    }

请问有没有大佬知道是哪里的问题

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档