我们有一个用c#编写的套接字客户端程序,我试图用Netty重写它。 c#登录方法如下所示:
public bool login(String prefix, string username, string password)
{
Send(String.Format("{0}{1},{2}\n", prefix, username, password));
try
{
var _4B = new byte[4];
_socket.Receive(_4B, 4, SocketFlags.None);
var len = ConvertToInteger(_4B);
var b = new byte[len];
_socket.Receive(b, len, SocketFlags.None);
GZipStream stream = new GZipStream(new MemoryStream(b, 0, len), CompressionMode.Decompress);
StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("GBK"));
String line = sr.ReadToEnd();
Window.MSG("Socket", "Feed login: " + line, MessageType.SystemMessage);
}
catch (SocketException e)
{
Window.MSG("Socket", "Socket Exception: " + e.Message, MessageType.Error);
return false;
}
return true;
}
上面的代码工作正常,然后我写了一个如下的Netty客户端:
public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("lengthFieldBasedFrameDecoder",
new LengthFieldBasedFrameDecoder(
Integer.MAX_VALUE, 0, 4, 0, 4));
/*
pipeline.addLast("gzipdeflater", ZlibCodecFactory
.newZlibDecoder(ZlibWrapper.GZIP)); */
pipeline.addLast("decoder", new StringDecoder(
Charset.forName("gbk")));
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new FeedClientHandler());
}
});
ChannelFuture future = bootstrap.connect().sync();
future.channel().writeAndFlush(login);
Thread.sleep(600000); // todo
} finally {
group.shutdownGracefully();
}
}
这个netty客户端无法正常工作,并且无法获得任何输出,我调试并发现LengthFieldBasedFrameDecoder.decode(ChannelHandlerContext ctx,ByteBuf in)方法返回null,因为in.readableBytes&lt; frameLengthInt(in.readableBytes = 1028,frameLengthInt = 1882716544)。
我不知道如何让它工作,有什么建议吗?提前谢谢:)
答案 0 :(得分:0)
感谢trustin和Suvitruf的评论,在将LengthFieldBasedFrameDecoder的ByteOrder设置为LITTLE_ENDIAN后,客户端正常工作!
pipeline.addLast("lengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 0, 4, 0, 4, true));