学习Netty之Netty客户端服务端Demo(以前写的了,发出来记录)

客户端代码:

public class NettyClient {
	
	
	public static void main(String[] args) {
		NioEventLoopGroup group  = new NioEventLoopGroup();
		try{
			Bootstrap b = new Bootstrap();
		
			b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,Delimiters.lineDelimiter()[0]));
					ch.pipeline().addLast(new StringDecoder());
					ch.pipeline().addLast(new ClientHandler());
					ch.pipeline().addLast(new StringEncoder());
				}
			});
		
			ChannelFuture f = b.connect("localhost", 10007).sync();
			String content  = "张三\r\n";
			
			ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();
			//将字节数组填充到buf中
			buf.writeBytes(content.getBytes(Charset.defaultCharset()));
			
			f.channel().writeAndFlush(buf);	
			
			
			f.channel().closeFuture().sync();
			Object result = f.channel().attr(AttributeKey.valueOf("key")).get();
			System.out.println(result);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			group.shutdownGracefully();
		}
		
	}
}

服务端代码:

public class NettyServer {
	public void start(){
	//服务端开启2个group,一个用于监听事件(单线程),一个用于处理I/O
		EventLoopGroup parent = new NioEventLoopGroup(1);
		EventLoopGroup child = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(parent, child).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
					ch.pipeline().addLast(new NettyServerHandler());
					ch.pipeline().addLast(new StringEncoder(Charset.defaultCharset()));
				}
			});
			
			ChannelFuture future = b.bind(10007).sync();
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			parent.shutdownGracefully();
			child.shutdownGracefully();
		}
			
	}
	
	public static void main(String[] args) {
		NettyServer n = new NettyServer();
		n.start();
	}
	
}

ClientHandler代码

public class ClientHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
		System.out.println("--------------------------------------");
		System.out.println("客户端管道注册完毕"+ctx.channel().toString());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		System.out.println("客户端可用");

	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("客户端读取数据");
		ctx.channel().attr(AttributeKey.valueOf("key")).set(msg);
		ctx.channel().close();
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		super.channelUnregistered(ctx);
		System.out.println("客户端管道注销");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelInactive(ctx);
		System.out.println("客户端管道不可用");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
		System.out.println("客户端管道读取数据完毕");
	}
	
	
	
}

ServerHandler

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
		System.out.println("管道注册完毕"+ctx.channel().toString());
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelUnregistered(ctx);
		System.out.println("管道注销完毕");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelActive(ctx);
		System.out.println("管道变得可用");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		System.out.println("管道变得不可用");

	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("====================读取数据");
		if(msg instanceof ByteBuf){
			ByteBuf b = (ByteBuf)msg;
			String content = b.toString(Charset.defaultCharset());
			System.out.println(content);
			String s = "李四\r\n";
			ctx.channel().writeAndFlush(s);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		System.out.println("管道读数据完毕");

	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值