Netty3学习笔记(二) --- Netty Helloworld入门

本文深入介绍了Netty框架,一个基于Java NIO的高性能网络应用框架。Netty简化了网络编程,提供了一种易于使用且高度可扩展的方式。文章涵盖了Netty在分布式进程通信、游戏服务器开发等领域的应用,并通过HelloWorld案例展示了服务端和客户端的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Netty简介

  Netty是基于Java NIO的网络应用框架.
  Netty是一个NIO client-server(客户端服务器)框架,使用Netty可以快速开发网络应用,例如服务器和客户端协议。
  Netty提供了一种新的方式来使开发网络应用程序,这种新的方式使得它很容易使用和有很强的扩展性。
  Netty的内部实现是很复杂的,但是Netty提供了简单易用的api从网络处理代码中解耦业务逻辑。
  Netty是完全基于NIO实现的,所以整个Netty都是异步的。

2、netty可以运用在那些领域?

 1.1 分布式进程通信

   例如: hadoop、dubbo、akka等具有分布式功能的框架,底层RPC通信都是基于netty实现的。

 1.2 游戏服务器开发

3、netty服务端hello world案例

代码示例:

/**
 	* netty服务端
	 */
	public class Server {

	public static void main(String[] args) {

		//服务类
		ServerBootstrap bootstrap = new ServerBootstrap();
		
		//boss线程监听端口,worker线程负责数据读写
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		
		//设置niosocket工厂
		bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));
		
		//设置管道的工厂
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			@Override
			public ChannelPipeline getPipeline() throws Exception {

				ChannelPipeline pipeline = Channels.pipeline();
				pipeline.addLast("decoder", new StringDecoder());
				pipeline.addLast("encoder", new StringEncoder());
				pipeline.addLast("helloHandler", new HelloHandler());
				return pipeline;
			}
		});	
		bootstrap.bind(new InetSocketAddress(10101));	
		System.out.println("start!!!");	
	}}

	/**
 	 * 消息接受处理类
 	 */
	public class HelloHandler extends SimpleChannelHandler {

		/**
	 	* 接收消息
	 	*/
		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
			
		String s = (String) e.getMessage();
		System.out.println(s);
		//回写数据
		ctx.getChannel().write("hi");
		super.messageReceived(ctx, e);
		}

		/**
		 * 捕获异常
		 */
		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
			System.out.println("exceptionCaught");
			super.exceptionCaught(ctx, e);
		}

		/**
	 	* 新连接
	 	*/
		@Override
		public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			System.out.println("channelConnected");
			super.channelConnected(ctx, e);
		}

		/**
		 * 必须是链接已经建立,关闭通道的时候才会触发
	 	*/
		@Override
		public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			System.out.println("channelDisconnected");
			super.channelDisconnected(ctx, e);
		}

		/**
	 	* channel关闭的时候触发
	 	*/
		@Override
		public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			System.out.println("channelClosed");
			super.channelClosed(ctx, e);
		}
	}

4、netty客户端hello world案例

代码示例:

	/**
 	* netty客户端
 	*/
	public class Client {

		public static void main(String[] args) {
		
			//服务类
			ClientBootstrap bootstrap = new  ClientBootstrap();
		
			//线程池
			ExecutorService boss = Executors.newCachedThreadPool();
			ExecutorService worker = Executors.newCachedThreadPool();
		
			//socket工厂
			bootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));
		
			//管道工厂
			bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				pipeline.addLast("decoder", new StringDecoder());
				pipeline.addLast("encoder", new StringEncoder());
				pipeline.addLast("hiHandler", new HiHandler());
				return pipeline;
			}
		});
		
		//连接服务端
		ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 10101));
		Channel channel = connect.getChannel();
		
		System.out.println("client start");
		
		Scanner scanner = new Scanner(System.in);
		while(true){
			System.out.println("请输入");
			channel.write(scanner.next());
		}
	  }
	}

	/**
 	* 消息接受处理类
 	*/
	public class HiHandler extends SimpleChannelHandler {

		/**
		 * 接收消息
	 	*/
		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
			String s = (String) e.getMessage();
			System.out.println(s);
			super.messageReceived(ctx, e);
		}

		/**
	 	* 捕获异常
	 	*/
		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
			System.out.println("exceptionCaught");
			super.exceptionCaught(ctx, e);
		}

		/**
	 	* 新连接
	 	*/
		@Override
		public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			System.out.println("channelConnected");
			super.channelConnected(ctx, e);
		}

		/**
		 * 必须是链接已经建立,关闭通道的时候才会触发
	 	*/
		@Override
		public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			System.out.println("channelDisconnected");
			super.channelDisconnected(ctx, e);
		}

		/**
		 * channel关闭的时候触发
	 	*/
		@Override
		public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			System.out.println("channelClosed");
			super.channelClosed(ctx, e);
		}
	}

5、SimpleChannelHandler小结

	SimpleChannelHandler 负责处理消息接收和写
	{
		messageReceived(ChannelHandlerContext ctx, MessageEvent e)   接收消息
		exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)   捕获异常
		channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)  新连接,通常用来检测IP是否是黑名单
		channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)  链接关闭,可以再用户断线的时候清楚用户的缓存数据等,必须是链接已经建立,关闭通道的时候才会触发
		channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)   channel关闭的时候触发,无论连接是否成功都会调用关闭资源
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值