// 當(dāng)連接建立成功之后會調(diào)用這個方法初始化channel
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
ctx.channel().pipeline().remove(this); //嗯,當(dāng)前這個handler對這個channel就算是沒有用了,可以移除了。。。
ctx.channel().pipeline().addFirst(new HttpClientCodec()); //添加一個http協(xié)議的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);
}
}
}
這部分的內(nèi)容基本上就囊括了上面提到的所有的步驟。。。而且寫了一個發(fā)起http請求的靜態(tài)方法。。。到這里基本上一個基于長連接的http客戶端就算差不多了。。。最后再來一個響應(yīng)httpresponse的handler吧:
?。踛ava] 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());
}
}
}
}
評論
查看更多