1.构建Hello服务器
1.构建一对主从线程组(除此之外有单线程,多线程)
2.定义服务器启动类:设置主从组,设置nio双向通道,子处理器
3.设置助手类初始化器
4.监听启动和关闭服务器
package com.imooc.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class HelloServer {
public static void main(String[] args) throws Exception {
//1。定义一对主从线程组,主线程用于接收客户端连接,从用来处理任务
EventLoopGroup bossGroup=new NioEventLoopGroup();
EventLoopGroup workGroup=new NioEventLoopGroup();
//2.创建netty服务器,ServerBootstrap是一个启动类:设置主从组,设置nio双向通道,子处理器
ServerBootstrap serverBootstrap=new ServerBootstrap();
serverBootstrap.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new HelloServerInitializer());
//3.启动server,设置8088为启动的端口号,同时启动方式为同步
ChannelFuture channelFuture=serverBootstrap.bind(8088)
.sync();
//4.监听关闭的channel,并设置为同步方式
channelFuture.channel().closeFuture().sync();
}
}
2.设置初始化器HelloServerInitializer
1.通过SocketChannel去获取整个管道
2.通过管道添加对应的Hander
package com.imooc.netty;
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 HelloServerInitializer extends ChannelInitializer<SocketChannel>{
protected void initChannel(SocketChannel ch) throws Exception {
//1.通过SocketChannel去获取整个管道
//2.通过管道添加对应的Hander
ChannelPipeline channelPipeline=ch.pipeline();
channelPipeline.addLast("HttpServerCodec",new HttpServerCodec());
channelPipeline.addLast("customHander",new CustomHander());
}
}
3.自定义助手类
package com.imooc.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
public class CustomHander extends SimpleChannelInboundHandler<HttpObject> {
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
Channel channel= ctx.channel();
System.out.println(channel.remoteAddress());
ByteBuf content= Unpooled.copiedBuffer("Hello Netty....", 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);
}
}