码迷,mamicode.com
首页 > Web开发 > 详细

netty学习笔记

时间:2014-08-12 17:47:14      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   java   使用   os   io   数据   ar   cti   

1、在没有任何encoder、decoder的情况下,Netty发送接收数据都是按照ByteBuf的形式,其它形式都是不合法的。

ByteBuf result = (ByteBuf) msg;
byte[] data = new byte[result.readableBytes()];
result.readBytes(data);
String resultStr = new String(data);
// 接收并打印客户端的信息
System.out.println("Client said:" + resultStr);
// 释放资源,这行很关键
result.release();
		
// 向客户端发送消息
String response = "I am ok!";
// 在当前场景下,发送的数据必须转换成ByteBuf数组
ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
encoded.writeBytes(response.getBytes());
ctx.write(encoded);
ctx.flush();

2、接收发送数据操作都是通过handler实现的,handler在netty中占据了非常重要的位置。

class HelloServerInHandler extends ChannelInboundHandlerAdapter

3、netty的handler是基于事件触发的,例如当client连接server成功后,client中的HelloClientIntHandler的channelActive方法会自动调用。

// 接收server端的消息,并打印出来  
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
	System.out.println("client channelRead");
	ByteBuf result = (ByteBuf) msg;  
	byte[] data=new byte[result.readableBytes()];
	result.readBytes(data);
	System.out.println("Server said:" + new String(data));
	result.release();
}

4、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
	log.debug("InboundHandler1 channelRead "+ctx);
	ctx.fireChannelRead(msg);
}
	
	
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
	log.debug("InboundHandler2 channelRead "+ctx);
	ByteBuf result=(ByteBuf)msg;
	byte[] data=new byte[result.readableBytes()];
	String res=new String(data);
	System.out.println("Client said: "+res);
	result.release();
		
	ctx.write(msg);
}

5、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。

@Override
public void write(ChannelHandlerContext ctx, Object msg,
			ChannelPromise promise) throws Exception {
	log.debug("OutboundHandler1 write");
	String str="i am ok";
	ByteBuf encoded=ctx.alloc().buffer(str.length()*4);
	encoded.writeBytes(str.getBytes());
		
	ctx.write(encoded);
	ctx.flush();
}

6、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。

ChannelPipeline pipeline=ch.pipeline();
    
pipeline.addLast(new OutboundHandler1());
pipeline.addLast(new OutboundHandler2());
    
pipeline.addLast(new InboundHandler1());
pipeline.addLast(new InboundHandler2());

7、Encoder、Decoder的本质也是Handler,它们的执行顺序、使用方法与Handler保持一致。

   执行顺序是:Encoder 先注册的后执行,与OutboundHandler一致;Decoder是先注册的先执行,与InboundHandler一致。


netty学习笔记,布布扣,bubuko.com

netty学习笔记

标签:style   java   使用   os   io   数据   ar   cti   

原文地址:http://my.oschina.net/freegarden/blog/300348

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!