将 String 消息从我的 Netty 客户端发送到我的服务器

Send a String message from my Netty client to my server

我有一个 Netty 客户端和一个 Netty 服务器,在按照主要教程进行操作以获得 EchoClient / 服务器之后,我想制作它以便我的客户端在他第一次连接到它时向我的服务器发送消息.

这里是我的 ClientClassHandler 应该处理的方法:

 private final ByteBuf firstMessage;

    public ClientClassHandler() {
        firstMessage = Unpooled.buffer(ClientClass.SIZE);
        for (int i = 0; i < firstMessage.capacity(); i++) {
            firstMessage.writeByte((byte) i);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("Channel is active.");
        ctx.writeAndFlush(firstMessage);
    }

但是如您所见,教程使用了 ByteBuf 而使用 String 似乎不起作用!

以下是我如何在 ServerClassHandler 的方法中显示收到的消息:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    System.out.println(msg); 
}

但是当 String 用于 firstMessage 并在构造函数中初始化并发送时,我的服务器不显示任何内容!

我有什么不明白的?

如果你想发送一个字符串然后首先使用 Unpooled.copiedBuffer(string, charset)

将它转换成一个 ByteBuf

Netty 有一个 CharsetUtil 可以帮助解决这个问题

只想在 netty 中添加更多关于 String 的信息,

你可以将 Object 转换成 Bytebuff

 ByteBuf in = (ByteBuf) msg;
 String data = in.toString(CharsetUtil.UTF_8);

但是如果你有长字符串对象,我建议使用 StringEncoder 和 netty 的解码器和 LineBasedFrameDecoder 并将你的处理程序扩展到

SimpleChannelInboundHandler<String>