服务端基本代码流程
客户端流程去掉一个用来监听接受客户端请求的bossGroup事件循环组启动类也去掉对应的Sever用Bootstrap对象去实现
public class TestServer {
public static void main(String[] args) throws Exception {
//创建两个事件循环组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//创建一个服务端启动对象
ServerBootstrap serverBootstrap = new ServerBootstrap();
//将事件循环组和自己实现的通道初始化器添加到启动对象中
serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new TestServerInitializer());
//监听端口
ChannelFuture ch = serverBootstrap.bind(8083).sync();
ch.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
//建立连接后会调用初始化器的初始化方法
protected void initChannel(SocketChannel ch) throws Exception {
//给通道添加对应的编解码器
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("httpServerCodec",new HttpServerCodec());
//添加自己实现的额编解码器
pipeline.addLast("testHttpServerHandler",new TestServerHttpHandler());
}
}
public class TestServerHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
ByteBuf content = Unpooled.copiedBuffer("Hello World!",CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
ctx.writeAndFlush(response);
}
}