gpt4 book ai didi

java - 读取字节到 Netty 服务器

转载 作者:行者123 更新时间:2023-12-01 14:45:39 24 4
gpt4 key购买 nike

public class ServerPipelineFactory implements ChannelPipelineFactory {
@Override
public ChannelPipeline getPipeline() throws Exception {
PacketFrameDecoder decoder = new PacketFrameDecoder();
PacketFrameEncoder encoder = new PacketFrameEncoder();
return Channels.pipeline(decoder, encoder, new Handler());
}
}

和我的解码器

public class PacketFrameDecoder extends
ReplayingDecoder<PacketFrameDecoder.DecoderState> {
public enum DecoderState {
READ_CONTENT;
}

private int length;

public PacketFrameDecoder() {
super(DecoderState.READ_CONTENT);
}

@Override
protected Object decode(ChannelHandlerContext chc, Channel chnl,
ChannelBuffer cb, DecoderState state) throws Exception {
switch (state) {

case READ_CONTENT:

for (int i = 0; i < cb.capacity(); i ++) {
byte b = cb.getByte(i);
System.out.println((char) b);
}

return null;
default:
throw new Error("Shouldn't reach here.");
}
}
}

我发送消息

Socket fromserver = new Socket("localhost", 7283);
PrintWriter out = new PrintWriter(fromserver.getOutputStream(), true);
int data = 12;
out.write(data);
out.flush();
out.close();
fromserver.close();

但是当我获得字节时 - 我有 cb.capacity() = 256和消息“?0?0” System.out.println((char) b);

请帮忙

最佳答案

使用容量是错误的,它是缓冲区中的“最大”字节数。从位置 0 开始也是错误的,因为 readerIndex 可能位于其他位置。请阅读 ChannelBuffer 的 apidocs,其中详细解释了所有这些内容。

关于java - 读取字节到 Netty 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15459387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com