我正在尝试使用最新的netty(4.1.5)设置基本的netty UDP服务器。我希望能够做的就是接收数据包并在控制台中显示内容。
我有两个课程如下;
public final class UdpServer {
private static final int PORT = Integer.parseInt(System.getProperty("port", "6565"));
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new UdpServerHandler());
b.bind(PORT).sync().channel().closeFuture().await();
} finally {
group.shutdownGracefully();
}
}
}
处理程序类如下;
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
static ByteBuf buf;
@Override
public void channelRead0 (ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
System.err.println ("Messaged received on " + new Date() + ":\r");
buf = packet.content();
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
buf.retain();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
System.err.println (buf.toString());
buf.release();
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
现在,每当我发送包含单词heelo的字节数据包时,我总会收到以下消息
Messaged received on Sun Sep 04 23:35:05 BST 2016:
SimpleLeakAwareByteBuf(PooledUnsafeDirectByteBuf(ridx: 5, widx: 5, cap: 2048))
我认为ridx和widx指的是你好的5个字符?
有人可以查看我的代码或进一步了解这个问题吗?感谢
答案 0 :(得分:0)
如果要将内容打印为字符串,请使用buf.toString(Charset)