一、Server端的编程模型

  • 示例代码1
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>(){
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
               p.addLast(new TimeServerHandler());
}
});
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}

由ServerBootstrap作为入口,用链式编程方式,分别调用group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler().

childHander()方法相当重要的方法,开发人员入手的地方,采用面向接口的方式,让开发人实现ChannelInitializer接口,实现initChannel(SocketChannel ch)方法,把自己的Handler通过channelPipeline().addLast(new TimeServerHandler())来实现事件处理。

  • 示例代码2
@Sharable
public class TimeServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelActive(final ChannelHandlerContext ctx) {
final ByteBuf time = ctx.alloc().buffer(4); // (2)
time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)); final ChannelFuture f = ctx.writeAndFlush(time); // (3)
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
assert f == future;
ctx.close();
}
}); // (4)
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

二、client编程模型

  • 代码示例3
public class TimeClient {

	public static void main(String[] args) throws Exception {
new TimeClient().bind();
} private void bind() throws InterruptedException{
String host = "localhost";
int port = Integer.parseInt("8080");
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new channelHandler()); // 启动客户端
ChannelFuture f = b.connect(host, port).sync(); // (5) // 等待连接关闭
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
} private class channelHandler extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());
}
}
}
 
public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf m = (ByteBuf) msg; // (1)
try {
long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
System.out.println(sdf.format(new Date(currentTimeMillis)));
ctx.close();
} finally {
m.release();
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

深入学习netty系列(1)的更多相关文章

  1. Netty系列之Netty线程模型

    Reference: http://www.infoq.com/cn/articles/netty-threading-model 1. 背景 1.1. Java线程模型的演进 1.1.1. 单线程 ...

  2. 【读后感】Netty 系列之 Netty 高性能之道 - 相比 Mina 怎样 ?

    [读后感]Netty 系列之 Netty 高性能之道 - 相比 Mina 怎样 ? 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商 ...

  3. 1. 彤哥说netty系列之开篇(有个问卷调查)

    你好,我是彤哥,本篇是netty系列的第一篇. 欢迎来我的公从号彤哥读源码系统地学习源码&架构的知识. 简介 本文主要讲述netty系列的整体规划,并调查一下大家喜欢的学习方式. 知识点 ne ...

  4. 2. 彤哥说netty系列之IO的五种模型

    你好,我是彤哥,本篇是netty系列的第二篇. 欢迎来我的公从号彤哥读源码系统地学习源码&架构的知识. 简介 本文将介绍linux中的五种IO模型,同时也会介绍阻塞/非阻塞与同步/异步的区别. ...

  5. 3. 彤哥说netty系列之Java BIO NIO AIO进化史

    你好,我是彤哥,本篇是netty系列的第三篇. 欢迎来我的公从号彤哥读源码系统地学习源码&架构的知识. 简介 上一章我们介绍了IO的五种模型,实际上Java只支持其中的三种,即BIO/NIO/ ...

  6. 4. 彤哥说netty系列之Java NIO实现群聊(自己跟自己聊上瘾了)

    你好,我是彤哥,本篇是netty系列的第四篇. 欢迎来我的公从号彤哥读源码系统地学习源码&架构的知识. 简介 上一章我们一起学习了Java中的BIO/NIO/AIO的故事,本章将带着大家一起使 ...

  7. 5. 彤哥说netty系列之Java NIO核心组件之Channel

    你好,我是彤哥,本篇是netty系列的第五篇. 简介 上一章我们一起学习了如何使用Java原生NIO实现群聊系统,这章我们一起来看看Java NIO的核心组件之一--Channel. 思维转变 首先, ...

  8. 6. 彤哥说netty系列之Java NIO核心组件之Buffer

    --日拱一卒,不期而至! 你好,我是彤哥,本篇是netty系列的第六篇. 简介 上一章我们一起学习了Java NIO的核心组件Channel,它可以看作是实体与实体之间的连接,而且需要与Buffer交 ...

  9. 7. 彤哥说netty系列之Java NIO核心组件之Selector

    --日拱一卒,不期而至! 你好,我是彤哥,本篇是netty系列的第七篇. 简介 上一章我们一起学习了Java NIO的核心组件Buffer,它通常跟Channel一起使用,但是它们在网络IO中又该如何 ...

随机推荐

  1. ios-消息弹框之UIAlertView, UIActionSheet以及UIAlertController小结

    首先storyboard中创建对应按钮并拖线,来演示不同的效果 首先点击了actionSheet按钮效果如图 实现弹框需要遵守设置代理,遵守协议. 效果就是从底部向上弹起来的框框. 通过对按钮的点击输 ...

  2. Unable to get setting value Parameter name: profileName

    Today when I am building my application, everything works well but when I try to run Azure Worker Ro ...

  3. Java基础之读文件——使用通道随机读取文件(RandomFileRead)

    import java.nio.file.*; import java.nio.channels.FileChannel; import java.io.IOException; import jav ...

  4. Java基础之写文件——使用带缓冲的Writer写文件(WriterOutputToFile)

    控制台程序,将一列字符串写入到文件中. import java.io.*; import java.nio.file.*; import java.nio.charset.Charset; publi ...

  5. Lintcode: Segment Tree Build

    The structure of Segment Tree is a binary tree which each node has two attributes start and end deno ...

  6. For循环输出九九乘法表

    题:使用For循环输出九九乘法表 解析: 1*1=1 1*2=2  2*2=4 1*3=3  2*3=6  3*3=9 .... 1*9=9  ........ .....9*9=81 可以看做j*i ...

  7. FOJ 2013 11 月赛

    这套题目还是比较吊的,由于我的沙茶,还是很多没有做出来- -! C:逆序数 D:呵呵 A:妈蛋,自己精度没弄好,想到之前GCC的要加eps,就WA了几次后交Visual C++过了!C(n,m)p^m ...

  8. C++多线程调试和测试的注意事项

    在一个程序中,这些独立运行的程序片断叫作“线程”(Thread),利用它编程的概念就叫作“多线程处理”.利用线程,用户可按下一个按钮,然后程序会立即作出响应,而不是让用户等待程序完成了当前任务以后才开 ...

  9. struts_22_xwork校验器列表使用说明

    系统提供的校验器列表如下: required (必填校验器,要求field的值不能为null) requiredstring (必填字符串校验器,要求field的值不能为null,并且长度大于0,默认 ...

  10. oracle的表空间

    创建表空间 1:创建单个文件的表空间 CREATE TABLESPACE SAMPLE LOGGING DATAFILE 'D:\11.dbf' SIZE 5M REUSE EXTENT MANAGE ...