Netty5入门程序结构说明

要借助于Netty框架编写通信程序,入门阶段基本的程序结构包含4个类(服务器端两个,客户端两个)。然后我们依次说明服务器端和客户端的程序实现。

1、服务器端实现:

Server类:

/**
 * 
 */
package upup.me.netty.think01;

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;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author Administrator
 * @desc 服务器主服务类
 */
public class Server {

	/**
	 * 实现绑定端口启动监听服务
	 * 
	 * @param port
	 *            端口
	 */
	public void bind(int port) {

		// 定义主线程组
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		// 定义子线程组
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {

			// 定义启动对象
			ServerBootstrap b = new ServerBootstrap();

			// 设置启动对象的线程组和Socket参数
			b.group(bossGroup, workerGroup);
			// 设置通道类型
			b.channel(NioServerSocketChannel.class);
			// 设置Socket参数
			b.option(ChannelOption.SO_BACKLOG, 1024);
			// 设置处理类
			b.handler(new LoggingHandler(LogLevel.INFO));
			// 设置子线程处理类
			b.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					// 此处可以添加解码器
					// 设置实际的处理类
					ch.pipeline().addLast(new ServerHandler());
				}
			});

			// 绑定端口同步等待成功
			ChannelFuture f = b.bind(port).sync();

			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 退出,释放线程资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	/**
	 * 服务端测试入口方法
	 */
	public static void main(String[] args) {
		int port = 8080;
		if (null != args && args.length > 0) {
			port = Integer.valueOf(args[0]);
		}

		new Server().bind(port);
	}
}


ServerHandler类:

/**
 * 
 */
package upup.me.netty.think01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author Administrator
 * @desc 服务器端逻辑处理类
 */
public class ServerHandler extends ChannelHandlerAdapter {

	/**
	 * 覆盖channelRead方法,读取通道中的数据
	 */
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("服务器,收到的数据:" + body);
		ByteBuf resp = Unpooled.copiedBuffer("Server Send Data".getBytes());
		ctx.write(resp);
	}

	/**
	 * 覆盖channelReadComplete方法
	 */
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	/**
	 * 覆盖exceptionCaught方法
	 */
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		ctx.close();
	}
}


2、客户端实现:

Client类:

/**
 * 
 */
package upup.me.netty.think01;

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;

/**
 * @author Administrator
 * @desc 客户端主服务类
 */
public class Client {

	public void connect(int port, String host) {
		// 配置客户端的NIO线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			// 定义启动对象
			Bootstrap b = new Bootstrap();

			// 绑定线程组
			b.group(group);
			// 设置通道类型
			b.channel(NioSocketChannel.class);
			// 设置Socket参数
			b.option(ChannelOption.TCP_NODELAY, true);
			// 设置处理类
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new ClientHandler());
				}
			});

			// 发起异步连接操作
			ChannelFuture f = b.connect(host, port).sync();

			// 等待链路关闭
			f.channel().closeFuture().sync();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 退出,释放NIO线程组
			group.shutdownGracefully();
		}
	}

	/**
	 * 客户端测试入口方法
	 */
	public static void main(String[] args) {
		int port = 8080;
		if (null != args && args.length > 0) {
			try {
				port = Integer.valueOf(args[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		new Client().connect(port, "127.0.0.1");
	}

}

ClientHandler类:

/**
 * 
 */
package upup.me.netty.think01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * 
 * @author Administrator
 * @desc 客户端逻辑处理程序
 */
public class ClientHandler extends ChannelHandlerAdapter {

	/**
	 * 连接成功发送请求
	 */
	public void channelActive(ChannelHandlerContext ctx) {
		byte[] req = "Client Send Data".getBytes();
		ByteBuf buf = Unpooled.buffer(req.length);
		buf.writeBytes(req);
		ctx.writeAndFlush(buf);
	}

	/**
	 * 读取服务端的返回
	 */
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("客户端,读取到的返回:" + body);
	}

	/**
	 * 异常处理
	 */
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println("发生异常:" + cause.getMessage());
		ctx.close();
	}
}


运行结果:




依赖包:netty-all-5.0.0.Alpha2.jar




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值