簡體   English   中英

使用 Java 的普通 TCP 客戶端和 Netty 服務器之間的 Protobuf 消息交換

[英]Protobuf message exchange between plain TCP client & Netty Server using Java

我正在嘗試使用 Java 中的 Protobuf 消息交換格式在普通TCP客戶端和 Netty 服務器之間創建 TCP 套接字連接,但它不起作用。 當我使用 Netty 客戶端(而不是 TCP 客戶端)和 Netty 服務器時,它可以工作。

Netty 服務器端,在 ServerHandler class 中,我得到 Object "msg" 作為類型"PooledUnsafeDirectByteBuf" 現在,當我嘗試將其轉換為我的自定義 Protobuf object 時,它失敗並出現錯誤 - 'java.lang.ClassCastException: class io.netty.buffer.PooledUnsafeDirectByteBuf 無法轉換為 ZA2F2ED4F8EBC12ABCB4Z2C

public class ServerHandler extends ChannelInboundHandlerAdapter  {
---
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
--- 

客戶端代碼

Socket clientConnection = new Socket("localhost",SERVER_PORT);
ObjectOutputStream outToServer = new ObjectOutputStream(clientConnection.getOutputStream());
ProtoModel.writeTo(outToServer); //ProtoModel is the protobuf class

我認為這與 TCP 客戶端的 Protobuf 消息編碼和 Netty Server 端的解碼有關。 當我使用 Netty 客戶端(而不是普通的 TCP 客戶端)時,相同的服務器代碼可以工作。

Netty 客戶端代碼

EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer());
Channel ch = bootstrap.connect("localhost",SERVER_PORT).sync().channel();
ChannelFuture lastWriteFuture = ch.writeAndFlush(ProtoModel);
lastWriteFuture.channel().closeFuture().sync();

如果我需要任何其他輸入,請告訴我。 非常感謝。

我能夠解決這個問題。 我在下面發布解決方案。

服務器代碼

public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf buf = (ByteBuf) msg;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            ProtobufModel obj = ProtobufModel.parseFrom(ByteString.copyFrom(req));
}

Object 'msg' 在服務器端以 ByteBuf 格式接收。 然后需要將'ByteBuf'格式轉換為'ByteString',最后可以從'ByteString'格式中檢索ProtobufModel。

客戶代碼

SocketChannel channel = SocketChannel
                    .open(new InetSocketAddress(InetAddress.getByName("localhost"), SERVER_PORT));
          ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
          byteBuffer.put(ProtobufModel.toByteArray());
          byteBuffer.flip();
          channel.write(byteBuffer);

在客戶端,ProtobufModel 被轉換為 ByteBuffer 並傳遞給服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM