// 当连接建立成功之后会调用这个方法初始化channel
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
ctx.channel().pipeline().remove(this); //嗯,当前这个handler对这个channel就算是没有用了,可以移除了。。。
ctx.channel().pipeline().addFirst(new HttpClientCodec()); //添加一个http协议的encoder与decoder
ctx.channel().pipeline().addLast(new ReponseHandler()); //添加用于处理http返回信息的handler
Fjs.doIt(ctx.channel());
}
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
System.out.println(“disconnect ” + System.currentTimeMillis() / 1000);
}
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
// TODO Auto-generated method stub
System.out.println(“read ” + System.currentTimeMillis() / 1000);
}
public void channelReadComplete(ChannelHandlerContext ctx)
throws Exception {
// TODO Auto-generated method stub
}
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
throws Exception {
// TODO Auto-generated method stub
}
public void channelWritabilityChanged(ChannelHandlerContext ctx)
throws Exception {
// TODO Auto-generated method stub
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
// TODO Auto-generated method stub
System.out.println(“error ” + System.currentTimeMillis() / 1000);
}
}
}
这部分的内容基本上就囊括了上面提到的所有的步骤。。。而且写了一个发起http请求的静态方法。。。到这里基本上一个基于长连接的http客户端就算差不多了。。。最后再来一个响应httpresponse的handler吧:
[java] view plain copypackage fjs;
import java.nio.charset.Charset;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
public class ReponseHandler extends ChannelInboundHandlerAdapter{
ByteBuf buf = Unpooled.buffer();
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpResponse) {
DefaultHttpResponse response = (DefaultHttpResponse)msg;
}
if (msg instanceof HttpContent) {
DefaultLastHttpContent chunk = (DefaultLastHttpContent)msg;
buf.writeBytes(chunk.content());
if (chunk instanceof LastHttpContent) {
long now = System.currentTimeMillis();
long before = Fjs.time.get();
System.out.println(((double) now - (double)before) / 1000);
String xml = buf.toString(Charset.forName(“UTF-8”));
buf.clear();
Fjs.doIt(ctx.channel());
}
}
}
}
评论