初学Netty(杰哥好久不见)

一、我对Netty的理解:

  一个开发网络编程的框架,改善了NIO框架的缺点。

二、第一个netty小程序

  1.服务器启动类ServerBootstrap:在该类中配置服务器连接数,是否延迟,长连接?添加数据操作类等等

    

 1 1.定义一个端口
 2  *2.在该类构造方法中传入端口参数,并在该类构造时调用bind()方法初始化服务器端配置
 3  *3.在bind()方法中先实例两个EventLoopGroup(boss和worker)用来管理线程-----
 4  *        EventLoopGroup boss = new NioEventLoopGroup();
 5         EventLoopGroup worker = new NioEventLoopGroup();
 6    4.使用ServerBootstrap类来初始化netty服务器,并且开始监听端口的socket请求
 7            ServerBootstrap bootstrap = new ServerBootstrap();
 8    5.根据ServerBootstrap內封装好的方法设置服务器基础信息
 9            bootstrap.group(boss, worker);//boss和worker两个线程池
10         bootstrap.channel(NioServerSocketChannel.class);
11         bootstrap.option(ChannelOption.SO_BACKLOG, 1024); // 连接数
12         bootstrap.option(ChannelOption.TCP_NODELAY, true); // 不延迟,消息立即发送
13         bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // 长连接
14         bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
15             @Override
16             protected void initChannel(SocketChannel socketChannel) throws Exception {
17                 ChannelPipeline p = socketChannel.pipeline();创建Channel通道
18                 p.addLast(new NettyServerHandler()); //往通道中添加i/o事件处理类
19             }
20         });
21    6.配置好服务器,在服务器启动时绑定闯入的port端口,等待同步
22            ChannelFuture f = bootstrap.bind(port).sync();
23    7.如果绑定成功
24            if(f.isSuccess()){
25                
26            }
27            f.channel().closeFuture().sync();
28    8.优雅释放
29            boss.shutdownGracefully();
30         worker.shutdownGracefully();

这样服务器端启动类就写好了,接下来写服务器端对客户端发来数据的操作类

  2.数据操作类ServerHandler:在该类中对客户端发来的数据进行操作,发送给客户端数据

  

 * 1.继承ChannelHandlerAdapter,重写channelRead方法
 * 			@Override
			public void channelRead(ChannelHandlerContext ctx, Object msg) {
 * 2.channelRead方法中的msg参数(服务器接收到的客户端发送的消息)强制转换成ByteBuf类型
 * 			ByteBuf buf = (ByteBuf) msg;
 * 3.写一个getMessage(ByteBuf xx)方法(返回String),在该方法中:
 * 				---首先通过ByteBuf类的readBytes()方法将msg转换成字节数组
 * 						byte[] con = new byte[buf.readableBytes()];
						buf.readBytes(con);
			   	---返回String,指定编码(有可能出现不支持的编码类型异常,所以要trycatch)
			   			new String(con,"UTF-8");
	4.对已经转换成String类型的数据进行操作
			System.out.println("服务器接收到消息:" + recieved);
 * 	5.服务端往客户端发送数据(数据类型ByteBuf)
 * 		try {
			ctx.writeAndFlush(getSendByteBuf("APPLE"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	6.	getSendByteBuf(String xxx)方法将服务端发送的数据转换成ByteBuf类型
		byte[] req = message.getBytes("UTF-8");
		ByteBuf pingMessage = Unpooled.buffer();
		pingMessage.writeBytes(req);
		return pingMessage;
 */

  以上两步就完成了对Netty服务器端的基本配置,接下来编写客户端代码,首先是客户端启动类

  3.ClientBootstrap,跟第一步写ServerBootstrap类类似

  

 *1.定义两个变量:客户端端口号和服务器IP地址
 *2.在构造方法中传入这两个参数,在该类构造的同时启动start()方法(start()方法要抛出线程中断异常)
 *3.在start()方法中实例客户端线程对象
 *				EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
  4.实例客户端启动类:Bootstrap
  				Bootstrap bootstrap = new Bootstrap();
  				对启动信息进行配置:
  				bootstrap.channel(NioSocketChannel.class);
				bootstrap.group(eventLoopGroup);
				bootstrap.option(ChannelOption.SO_KEEPALIVE, true);//长连接
				bootstrap.remoteAddress(host, port);//服务器主机地址端口号
				bootstrap.handler(new ChannelInitializer<SocketChannel>() {//添加客户端数据处理类
				@Override
				protected void initChannel(SocketChannel socketChannel)
						throws Exception {					
					socketChannel.pipeline().addLast(new NettyClientHandler());
				}
			});
	5.在客户端启动时连接服务器ip和端口
				ChannelFuture cf = bootstrap.connect(host,port).sync();
	6.如果连接成功
				if(cf.isSuccess()){
				
				}
	7.关闭通道
				cf.channel.closeFuture().sync();
	8.优雅释放
				eventLoopGroup.shutdownGracefully();
 */

  4.最后写客户端数据操作类,ClientHandler

 *1.首先跟服务器操作类一样继承ChannelHandlerAdapter类,重写channelRead和channelActive两个方法
 *其中channelActive方法是用来发送客户端信息的,channelRead方法客户端是接收服务器数据的
 *2.先声明一个全局变量firstMessage,用来接收客户端发出去的信息的值
 *3.在channelActive方法中把要传输的数据转化为字节数组
 *		byte[] data = "服务器,给我一个APPLE".getBytes();
 *		firstMessage = Unpooled.buffer();
		firstMessage.writeBytes(data);
 *		ctx.writeAndFlush(firstMessage);
 *4.在channelRead方法中
 *		ByteBuf buf = (ByteBuf) msg;
	String rev = getMessage(buf);
	System.out.println("客户端收到服务器数据:" + rev);
	}
	private String getMessage(ByteBuf buf) {
		byte[] con = new byte[buf.readableBytes()];
		buf.readBytes(con);
		try {
			return new String(con, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
 */

  

  ok,第一个netty程序完成

  

 

posted @ 2017-02-15 13:08  Sisyphus_qiu  阅读(1940)  评论(0编辑  收藏  举报