Netty(一)Hello Discard Server

4 篇文章 0 订阅
4 篇文章 0 订阅

其实在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();
		}
	}
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值