netty3入门案例

Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络服务器和客户端程序。也就是说它是一个NIO框架,使用它可以简单快速地开发网络应用程序。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。学习netty前需要对NIO理解得很透彻,可参考我另一篇文章java NIO或者网上找资料学习一下。

下面分别以类似HelloWorld的最基础案例来学习,案例是基于网络通信的。所以有Server端和Client端,当然客户端可以在本地使用telnet命令来测试。netty3和netty5版本在API上区别较大,下面是Netty3的一个例子。

Netty3 Server:

public class Server {
	public static void main(String[] args) {
		// 服务类,用于启动netty 在netty5中同样使用这个类来启动
		ServerBootstrap bootstrap = new ServerBootstrap();
		// 新建两个线程池  boss线程监听端口,worker线程负责数据读写
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		// 设置niosocket工厂  类似NIO程序新建ServerSocketChannel和SocketChannel
		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());  //添加一个Handler来处理客户端的事件,Handler需要继承ChannelHandler
				return pipeline;
			}
		});
		bootstrap.bind(new InetSocketAddress(10101));
		System.out.println("start!!!");
	}
}
HelloHandler类:

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("HelloWorld");
		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);
	}
}
到这里就可以启动Server端了。

netty3 Client:

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());
		}
	}
}
客户端不断等待终端输入并写入通道。服务端接收到新的输入后会获取到输入的信息。对服务端的回写客户端也需要一个Handler来处理。下面是这客户端HiHandler的代码

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);
	}
}
至此就完成了Netty3的一个最基础的例子。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值