Netty学习-CS模式的简单示例

本文介绍了一个使用Netty实现的时间服务器及客户端程序。该程序能够接收客户端请求并返回当前时间。服务器利用NioEventLoopGroup处理网络事件,并通过TimeServerHandler处理接收到的消息。

package timeserver;

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 TimeServer {
	
	public void bind(int port) throws Exception {
		
		//NioEventLoopGroup 是个线程组,它包含了一组NIO线程组,专门用于网络事件的处理,实际上它们是Reactor线程组。
		//两个线程组一个用于服务端接收客户端的连接,另一个用于进行SocketChannel的网络读写
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			//启动NIO服务的辅助启动类
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new ChildChannelHandler());
			
			//启动辅助类配置完成之后,调用bind方法绑定监听端口,调用sync同步阻塞方法等待绑定操作完成
			ChannelFuture f = b.bind(port).sync();
			
			//阻塞,等待服务端链路关闭之后main函数才退出
			f.channel().closeFuture().sync();
			
			
		} finally {
			//线程组退出,释放资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
		
	}
	
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			arg0.pipeline().addLast(new TimeServerHandler());
		}
		
	}
	
	
	public static void main(String[] args) throws Exception {
		int port = 8081;
//		if (args != null && args.length > 0) {
//			
//		}
		new TimeServer().bind(port);
	}
	
}



package timeserver;

import java.text.SimpleDateFormat;
import java.util.Date;

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

public class TimeServerHandler extends ChannelHandlerAdapter {
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//对msg进行强制类型转换,ByteBuf的readableBytes方法可以获取缓冲区可读的字节数,
		//根据可读的字节数创建byte数组,通过ByteBuf的readBytes方法将缓冲区中的字节数组复制到新建的bytes数组中。
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		
		String body = new String(req, "UTF-8");
		System.out.printf("THE TIME SERVER RECEIVE ORDER %s", body);
	
		SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
		String currentTime = "QUERY TIME ORDER".equals(body) ? f.format(new Date()) : "BAD QUERY ORDER";
		
		//把字符串构造成ByteBuf对象
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		//发送应答消息,不把消息写入SocketChannel中,调用write方法只是把待发送的消息放到发送缓冲数组中
		ctx.write(resp);
	}
	
	
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //flush将缓冲区中的消息全部写入到SocketChannel中
    	ctx.flush();
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //释放资源
    	ctx.close();
    }
}

package timeserver;

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;

public class TimeClient {
	
	public void connect(int port, String host) throws Exception {
		
		//客户端I/O读写的线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			//辅助启动类
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				
				//内部类初始化Channel,设置handler
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new TimeClientHandler());
				}
				
			}); 
			
			ChannelFuture f = b.connect(host, port).sync();
			f.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8081;
		new TimeClient().connect(port, "127.0.0.1");
	}

}


package timeserver;

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

public class TimeClientHandler extends ChannelHandlerAdapter {
	
	private final ByteBuf firstMessage;
	
	public TimeClientHandler() {
		byte[] req = "QUERY TIME ORDER".getBytes();
		firstMessage = Unpooled.buffer(req.length);
		firstMessage.writeBytes(req);
	}
	
	//收到服务端的应答消息之后ChannelRead方法被调用
    @Override
    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("Now is : " + body);
    }
	
    //当客户端和服务端TCP链路建立成功之后, Netty的NIO线程会调用channelActive方法,发送消息给服务端
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(firstMessage);
    }

  
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值