netty网络模型

netty网络模型

简单版

在这里插入图片描述

进阶版

在这里插入图片描述

详细版

在这里插入图片描述

模型再说明

在这里插入图片描述

示例代码

Server

package nettyDemo01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
	public static void main(String[] args) {
		// 创建BossGroup和WorkerGroup
		// bossGroup只处理连接请求,workerGroup处理业务逻辑,都是无限循环
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGoup = new NioEventLoopGroup();
		try {
			// 创建服务器端启动对象,配置参数
			ServerBootstrap bootstrap = new ServerBootstrap();
			// 使用链式编程来进行设置
			bootstrap.group(bossGroup, workerGoup).channel(NioServerSocketChannel.class)// 使用NioSocketChannel作为服务器通道实现
					.option(ChannelOption.SO_BACKLOG, 128)// 设置线程队列链接个数
					.childOption(ChannelOption.SO_KEEPALIVE, true)// 设置保持活跃状态
					.childHandler(new ChannelInitializer<SocketChannel>() {// 创建一个通道测试对象
						// 给pipeline设置处理器
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new NettyServerHandler());
						}
					});// 给BossGroup和WorkerGroup的EventLoop对应管道设置处理器

			System.out.println("服务器准备好了...");
			// 绑定端口并同步,生成ChannelFuture对象
			ChannelFuture cf = bootstrap.bind(9999).sync();
			// 对关闭通道进行监听
			cf.channel().closeFuture().sync();
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			bossGroup.shutdownGracefully();
			workerGoup.shutdownGracefully();
		}
	}
}

ServerHandler

package nettyDemo01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/*
 * 1.自定义一个handler需要继承某种HandlerAdapter
 * 2.这时他才能成为一个Handler
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
	/*
	 * 读取数据 1.ChannelHandlerContext上下文对象,含有管道,通道 2.客户端发送的数据,默认是Object
	 */
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("server ctx =" + ctx);
		// 将msg转为ByteBuf(netty提供,不是NIO提供)
		ByteBuf buf = (ByteBuf) msg;
		System.out.println("客户端发送消息: " + buf.toString(CharsetUtil.UTF_8));
		System.out.println("客户端地址: " + ctx.channel().remoteAddress());
	}

	// 读取完毕操作
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 将数据写入到缓冲,并刷新
		// 一般需要编码
		ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端", CharsetUtil.UTF_8));
	}

	// 异常处理
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}

Client

package nettyDemo01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
	public static void main(String[] args) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap bootStrap = new Bootstrap();
		bootStrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
			protected void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new NettyClientHandler());
			};
		});

		System.out.println("客户端OK...");
		// 启动客户端链接服务端
		ChannelFuture cf = null;
		try {
			cf = bootStrap.connect("127.0.0.1", 9999).sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			// 监听关闭
			cf.channel().closeFuture().sync();
			group.shutdownGracefully();
		}
	}
}

ClientHandler

package nettyDemo01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
	// 通道就绪就会触发该方法
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("client " + ctx);
		ctx.writeAndFlush(Unpooled.copiedBuffer("hello server", CharsetUtil.UTF_8));
	}

	// 当通道有读取事件触发
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		System.out.println("服务器回复: " + buf.toString(CharsetUtil.UTF_8));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值