欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Netty 入门demo

程序员文章站 2022-04-24 11:01:05
...

信息的发送与返回(这里有问题,但是没有发现问题在哪里,暂时存一下代码,后期深入研究的时候,再来补)

public class TimeClient {
	public void connect(int port,String host) throws InterruptedException {
		//配置客户端的nio线程组
		EventLoopGroup group=new NioEventLoopGroup();
		try {
			Bootstrap b=new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				public void initChannel(SocketChannel ch) throws Exception{
					 ch.pipeline().addLast(new TimeClientHandler());
				}
			});
			System.out.println("客户端启动成功,准备连接...");
			//发起异步连接操作。
			ChannelFuture f=b.connect(host,port).sync();
			System.out.print("连接成功\n");
			//等待客户端链路关闭
			f.channel().closeFuture().sync();
		}finally {
			group.shutdownGracefully();
		}
	}
	public static void main(String []args) throws InterruptedException {
		new TimeClient().connect(8888, "127.0.0.1");
	}
}
public class TimeClientHandler extends ChannelHandlerAdapter{
	private static final Logger logger=Logger.getLogger(TimeClientHandler.class.getName());
	private final ByteBuf firstMessage;
	public TimeClientHandler() {
		System.out.println("发送端 处理器 初始化...");
		byte[]req="query time order".getBytes();
		firstMessage=Unpooled.buffer(req.length);
		firstMessage.writeBytes(req);
	}
	//向服务器发送信息;
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 System.out.println("发送消息");
	        ctx.write(firstMessage);
	        ctx.flush();
	    }
	 //接受服务器的信息
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("SimpleClientHandler.channelRead");
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        System.out.println("Server said:" + new String(result1));
        result.release();
    }
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
public class TimeServer {
	public void bind(int port) throws InterruptedException {
		//两个线程组,reactor线程组,一个负责接受,另外一个负责独写。
		EventLoopGroup bossGroup=new NioEventLoopGroup();
		EventLoopGroup workerGroup=new NioEventLoopGroup();
		//这里好像是注册,设置参数,绑定端口等等。
		ServerBootstrap b=new ServerBootstrap();  //它好像是一个辅助启动类。
		b.group(bossGroup,workerGroup)
		.channel(NioServerSocketChannel.class)
		.option(ChannelOption.SO_BACKLOG, 1024)
		.childHandler(new ChildChannelHandler());
		//绑定端口,同步等待成功。
		ChannelFuture f=b.bind(port).sync();
		
		System.out.print("等待客户端 连接...\n");
		//等待服务器端口监听关闭。
		f.channel().closeFuture().sync();
		//退出释放 资源
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			arg0.pipeline().addLast(new TimeServerHandler());
		}
		
	}
	public static void main(String []args) {
		int port=8888;
		try {
			new TimeServer().bind(port);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
public class TimeServerHandler extends ChannelHandlerAdapter {

	public void channeilRead(ChannelHandlerContext ctx,Object msg) throws UnsupportedEncodingException {
		ByteBuf buf=(ByteBuf) msg;  //缓冲,处理接受到的消息。
		byte[] req=new byte[buf.readableBytes()]; //转成byte类型吗?
		buf.readBytes(req); //将buf里面的内容,放到byte中。
		String body=new String(req,"UTF-8"); //又将字节组 转为字符串,编码方式设置。
		System.out.println("server 收到的内容:"+body);
		
		String currentTime="query time order".equalsIgnoreCase(body)?new Date(
				System.currentTimeMillis()).toString():"bad order";
		ByteBuf resp=Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp); //将时间转化成字节码,然后传入buffer,然后返回给客户端。
	}
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }

}

 

相关标签: 框架