其实在Netty里面会有很多的回调函数和异步调用,这个是Netty框架最值得学习的地方
不管是Server还是Client,总会在开始的时候有这么一段:
<pre name="code" class="java">EventLoopGroup group = new NioEventLoopGroup();// 也就是用于处理非阻塞IO(NIO)的线程池
ServerBootstrap sb = new ServerBootstrap(); // 也就是一个封装好所有操作和对象的server或者client端的类
// Bootstrap sb = new Bootstrap();
sb.group(group) // 绑定线程池
.channel(NioServerSocketChannel.class) // 设置channel对象
.handler(new SimpleInitializer())); // ChannelInitializer对象的子类,用于设置处理消息流的即最新从ChannelSocket对象中获取到的ChannelPipeline的不同handler实例
上面所示的就是Netty教程上最普遍的程序源码,下面给出服务器端和客户端的详细代码,具体部分会在后续展开讨论:
服务器端:
public class DiscardServer {
private static final int PORT_NUM = Integer.parseInt(System.getProperty("port", "6767"));
public void run() throws CertificateException, SSLException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new DiscardServerInitializer());
// bind and start to accept incoming connections
ChannelFuture cf = sb.bind(PORT_NUM).sync();
// Wait until the server socket is closed
// 本例中,下面一行代码永远不会发生,但可以用于正常关闭server
// 监听服务关闭监听
cf.channel().closeFuture().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
客户端:
public class DiscardClient {
private static final String REMOET_HOST = System.getProperty("host", "127.0.0.1");
private static final int REMOTE_PORT = Integer.parseInt(System.getProperty("port", "6767"));
public static final int BUFFER_SIZE = Integer.parseInt(System.getProperty("size", "8192"));
public void run() throws SSLException, CertificateException, InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bs = new Bootstrap();
bs.group(group)
.channel(NioSocketChannel.class)
.handler(new DiscardClientInitializer());
// make the connection attempt
ChannelFuture f = bs.connect(REMOET_HOST, REMOTE_PORT).sync();
// Wait until the connection is closed
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}