Netty-3-服务端接受并打印telnet传递过来的字符串

数据的流通是以byte的形式流通的,本文将通过字节转换成字符串new String的方式打印出来

第一个handler,首先,往pipeline里加了第二个handler,也就是说,pipeline里有两个handler了,handler1负责接收最原始的ByteBuf对象(msg),似乎对neety来说第一个handler永远都是ByteBuf,然后将ByteBuf转换成字符串,打印该字符串,打印完毕之后,将该字符串传递到handler2中

public class MyServerHandler1 implements ChannelInboundHandler {
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		//动态往pipeline里添加一个handler
		ctx.pipeline().addLast(new MyServerHandler2());
	}
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//因为是第一个handler,所以msg是ByteBuf
		ByteBuf bb = (ByteBuf) msg;
		int len = bb.readableBytes();
		byte[] bytes = new byte[len];
		bb.readBytes(bytes);
		String value = new String(bytes);
		System.out.println("channelRead值:" + value);
		//将一个String类型的字符串传递给第二个handler
		ctx.fireChannelRead(value);
	}

第二个handler

public class MyServerHandler2 implements ChannelInboundHandler {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//msg是从handler1中传递过来的String类型字符串
		System.out.println(objName + ":channelRead,值:" + msg);
		ctx.fireChannelRead(msg);
	}

main方法

	public static void main(String[] args) throws InterruptedException {
		EventLoopGroup boosGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		ServerBootstrap b = new ServerBootstrap();
		//此处new MyServerHandler1
		b.group(boosGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new MyServerHandler1());
		ChannelFuture f = b.bind(9999).sync();
		f.channel().closeFuture().sync();

启动main方法,telnet命令,从键盘上按哪个字母,控制台就会打印哪个字母

发布了157 篇原创文章 · 获赞 26 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u011624903/article/details/51274054