JAVA通信系列三:Netty入门总结
一、Netty学习资料
书籍《Netty In Action中文版》
对于Netty的十一个疑问
http://news.cnblogs.com/n/205413/
深入浅出Netty
http://wenku.baidu.com/view/7765bc2db4daa58da0114a4c.html
Netty了解与小试
http://www.cnblogs.com/xd502djj/archive/2012/06/25/2561318.html
Netty系列之Netty高性能之道【精彩】
http://www.infoq.com/cn/articles/netty-high-performance/
Netty系列之Netty 服务端创建【精彩】
http://www.infoq.com/cn/articles/netty-server-create
Netty 5用户指南
http://ifeve.com/netty5-user-guide/
基于Netty5.0入门案例六之NettyServer群发消息
http://www.bubuko.com/infodetail-575271.html
Netty5入门学习笔记002-TCP粘包/拆包问题的解决之道(上)
http://my.oschina.net/imhoodoo/blog/357290
基于Netty与RabbitMQ的消息服务
http://www.cnblogs.com/luxiaoxun/archive/2015/01/28/4257105.html
基于Netty5.0入门案例五之NettyServer字符串编码器
http://www.itstack.org/?post=9
二、代码示例
Hello world
1.编写处理器 DiscardServerHandler extends ChannelHandlerAdapter
2.编写Main方法,启动DiscardServerHandler
Echo
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) { // (1)
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
ReferenceCountUtil.release(msg); // (2)
}
}
Time
@Override
public void channelActive(final ChannelHandlerContext ctx) { // (1)
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)
}
流数据的传输处理【分包,黏包】
1.ChannelHandler有2个生命周期的监听方法:handlerAdded()和handlerRemoved()。你可以完成任意初始化任务只要他不会被阻塞很长的时间。
public class TimeClientHandler extends ChannelHandlerAdapter {
private ByteBuf buf;
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
buf = ctx.alloc().buffer(4); // (1)
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
buf.release(); // (1)
buf = null;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf m = (ByteBuf) msg;
buf.writeBytes(m); // (2)
m.release();
if (buf.readableBytes() >= 4) { // (3)
long currentTimeMillis = (buf.readInt() - 2208988800L) * 1000L;
System.out.println(new Date(currentTimeMillis));
ctx.close();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
2.TimeClientHandler拆分成2个处理器:TimeDecoder处理数据拆分的问题,TimeClientHandler原始版本的实现
public class TimeDecoder extends ByteToMessageDecoder { // (1)
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // (2)
if (in.readableBytes() < 4) {
return; // (3)
}
out.add(in.readBytes(4)); // (4)
}
}
用POJO代替ByteBuf
posted on 2016-09-06 11:01 ITFLY8架构师之家 阅读(2032) 评论(1) 编辑 收藏 举报