我们用一个新的子类SimpleChannelInboundHandler。提供了
package http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import netty.Nhandler;
public class Hser {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(2);
EventLoopGroup workGroup = new NioEventLoopGroup(2);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
// .option(ChannelOption.SO_BACKLOG,128)
// .childOption(ChannelOption.SO_KEEPALIVE,true)
.childHandler(new Cinit());
System.out.println("server is ready");
ChannelFuture channelFuture = serverBootstrap.bind(12312).sync();//server
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println("监听端口成功");
}else {
System.out.println("失败了");
}
}
});
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
package http;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class Cinit extends ChannelInitializer<SocketChannel> {//abstract
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec", new HttpServerCodec());//auto
pipeline.addLast("handler", new Hhandler());
}
}
package http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;
public class Hhandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpRequest){
System.out.println("msg.getClass() = " + msg.getClass());
System.out.println("ctx.channel().remoteAddress() = " + ctx.channel().remoteAddress());
ByteBuf buf = Unpooled.copiedBuffer("我是总部", Charset.forName("gbk"));
DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,buf);//type
defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
ctx.writeAndFlush(defaultFullHttpResponse);//type
}
}
}
init为的是总体的处理流程
关注自己写的类