dependencies {
testCompile(
"junit:junit:4.12"
)
// https://mvnrepository.com/artifact/io.netty/netty-all
compile group: 'io.netty', name: 'netty-all', version: '4.1.32.Final'
}
服务端
处理的过程:
- 父事件组接受客户端的连接请求,
- 连接上后就交由子事件组进行处理(在处理请求时是有处理器来进行处理的)
- 创建父处理器,子处理器
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TestServer {
public static void main(String[] args) throws Exception {
//创建两个事件处理组
//父类用来处理客户端的连接操作,连接后交给客户端处理
//子类处理客户端的请求
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
//创建服务启动类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//为服务设置事件处理组、管道类型
serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
//设置子处理器
.childHandler(new TestServerInitialHandler());
//启动
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
}finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
}
处理器
TestServerInitialHandler
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 TestServerInitialHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("httpCodec",new HttpServerCodec());
pipeline.addLast("TestHttpServerHandler",new TestHttpServerHandler());
}
}
TestHttpServerHandler
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;
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
//设置返回的数据
ByteBuf buffer = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
//创建返回的response对象
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,buffer);
//设置消息头
response.headers().set(HttpHeaderNames.CONTENT_TYPE,HttpHeaderValues.TEXT_PLAIN)
.set(HttpHeaderNames.CONTENT_LENGTH,buffer.readableBytes());
ctx.writeAndFlush(response);
}