java服务端(3)netty框架基础

netty各种对象:

Netty服务器创建流程:

创建步骤: 

  1、创建服务类bootstrap:

//服务类
ServerBootstrap bootstrap = new ServerBootstrap();

  2、两个重要的线程池:

//boss线程监听端口,worker线程负责数据读写
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService worker = Executors.newCachedThreadPool();

   3、给bootstrap 服务类 设置 一个 niosocket工厂

//给   bootstrap  服务类 设置 一个 niosocket工厂
bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));  
// 为这个工厂传入boss 和 worker 两个线程池
		

   4、给   bootstrap  服务类 设置管道的工厂

bootstrap.setPipelineFactory(new ChannelPipelineFactory() { ... }
		

         这个会传入一个匿名内部类,最终返回的是一个 ChannelPipeline  的管道,我们可以在这个管道自己加一些过滤器。

   5、 给 bootstrap 服务类绑定端口

bootstrap.bind(new InetSocketAddress(10101));

 

服务端启动的源代码:

    public static void main(String[] args) {

		//服务类
		ServerBootstrap bootstrap = new ServerBootstrap();
		
		//boss线程监听端口,worker线程负责数据读写
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		
		//给   bootstrap  服务类 设置 一个 niosocket工厂
		bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));  // 为这个工厂传入boss 和 worker 两个线程池
		
		//给   bootstrap  服务类 设置管道的工厂
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			@Override
			public ChannelPipeline getPipeline() throws Exception {      // 获取一个管道
				// 1、 新建一个管道 
				// 2、 为这个管道加过滤器
				ChannelPipeline pipeline = Channels.pipeline();
				pipeline.addLast("decoder", new StringDecoder());
				pipeline.addLast("encoder", new StringEncoder());
				pipeline.addLast("helloHandler", new HelloHandler());
				return pipeline;
			}
		});
		
		//给   bootstrap  服务类 绑定端口 
		bootstrap.bind(new InetSocketAddress(10101));
		System.out.println("start!!!");
		

	}

HelloHandler消息处理类:

         HelloHandler消息处理类,是在第四步的管道中加入的一个处理类。我们可以在这个处理类中重写相应的多个方法。

public class HelloHandler extends SimpleChannelHandler {
	/**
	 * 接收消息
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		/*
		 * 由于我们在 管道加了 new StringDecoder() 这两个过滤就不用这么麻烦了
		 * ChannelBuffer message = (ChannelBuffer)e.getMessage();
		 * String s = new String(message.array());
		*/
		
		System.out.println("messageReceive");
		
		// 当有异常出现的时候 就会执行exceptionCaught
		//int i = 1/0; 
		
		String s = (String) e.getMessage();
		System.out.println(s);
		
		//回写数据   我们加了new StringEncoder() 就不用这么麻烦
		//ChannelBuffer copiedBuffer = ChannelBuffers.copiedBuffer("hi".getBytes());
		// ctx.getChannel().write(copiedBuffer);

		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关闭的时候触发 ,就算没有连接成功,也需要Closed去释放资源
	 */
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("channelClosed");
		super.channelClosed(ctx, e);
	}
}

问题:

    问题1:这个bootstrap服务类怎么接受消息?

                是在 HelloHandler 中接受消息处理的

    问题2:在接收消息的时候我们一定需要通过 Buffer 和 Channel  才能进行消息的传输?

                 是的,不过我们可以通过在  ChannelPipeline 管道中加入  new StringDecoder(),new StringEncoder() 这两个管道节约我们的操作,具体代码可看上述服务端启动代码

    问题3:ChannelPipeline管道中过滤器的执行顺序:

            

 

 

操作执行过程:

     1、打开CMD -> telnet 127.0.0.1 10101 就可以连接这个服务端
           Console 会输出  HelloHandler.java 下的    => channelConnected
           
     2、在CMD 输入消息:
           Console 会输出  HelloHandler.java 下的    => messageReceive 和客户端输入的消息以及回显
         
     3、当有异常出现的时候 就会执行   channelClosed

           例如我们在 messageReceived 接收消息的时候执行  int i=1/0;就会抛出异常
   
     4、关闭已经连接的CMD窗口的时候 
          会先执行  channelDisconnected 
          再执行    channelClosed


     5、channelClosed 是在 channel关闭的时候触发 ,就算没有连接成功,也需要Closed去释放资源

 

额外的补充:

     1、SimpleChannelHandler 中的 channelDisconnected 的用处,当一个客户端恶意连接的时候,我们可以将这个恶意的客户端拉入黑名单中。以保证服务器的安全

     2、SimpleChannelHandler中的 channelClosed 和 channelDisconnected 的用处是当玩家下线的时候,我们可以在服务器清除玩家在服务器中的缓存等操作。

 

 

Netty客户端代码:

创建步骤:

  1、创建客户端服务类

ClientBootstrap bootstrap = new  ClientBootstrap();

  2、创建两个线程池:

ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService worker = Executors.newCachedThreadPool();

  3、为客户端服务类设置socket 工厂(与服务端不同的是一个Client)

bootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));

 

  4、设置管道工厂:

  5、连接服务端

ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 10101));

  6、获取一个会话(管道)

Channel channel = connect.getChannel();    // 获取一个会话 (管道)

  7、循环输入信息

while(true){
    System.out.println("请输入");
    channel.write(scanner.next());    // 向服务端发送数据
}

 

客服端启动源码:

        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());    // 向服务端发送数据
		}
	}

ClientHandler处理类:

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);
	}
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值