rzk · 2月20日 · 2021年本文共3380个字 · 预计阅读12分钟96次已读
Http实例
* 1)实例要求:使用IDEA创建Netty项目
* 2) Netty 服务器在8880端口监听,浏览器发出请求
* 'http://localhost.8880/ '
* 3)服务器可以回复消息给客户端"Hello!我是服务器5",并对特定请求资源进行过滤
* 4)目的: Netty可以做Http服务开发, 并且理解Handler实例和客户端及其请求的关系
TestServer
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;
/**
* 1)实例要求:使用IDEA创建Netty项目
* 2) Netty 服务器在8880端口监听,浏览器发出请求
* "http://localhost.8880/ '
* 3)服务器可以回复消息给客户端"Hello!我是服务器5",并对特定请求资源进行过滤
* 4)目的: Netty可以做Http服务开发, 并且理解Handler实例和客户端及其请求的关系
*/
/**
* @PackageName : com.rzk.netty.http
* @FileName : TestSerever
* @Description :
* @Author : rzk
* @CreateTime : 2021/2/19 18:55
* @Version : 1.0.0
*/
public class TestServer {
public static void main(String[] args) 睿共享throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
//创建一个serverBootstrap 用于启动服务器
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new TestServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8880).sync();
channelFuture.channel().closeFuture().sync(睿共享);
}finally {
bossGroup.shutdownGracefully();
workerGrou睿共享p.shutdownGracefully();
}
}
}
TestServerInitializer.java
/**
* @PackageName : com.rzk.netty.http
* @FileName : TestServerInitializer
* @Description :
* @Author : rzk
* @CreateTime : 2021/2/19 19:03
* @Version : 1.0.0
*/
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//向管道加入处理器
//得到管道
ChannelPipeline pipeline = ch.pipeline();
//加入netty 提供的httpServerCodec codec => [coder - decoder]
//HttpServerCodec 说明
//1.HttpServerCodec 是netty
pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
//2.增加一个自定义的handler
pipeline.addLast("MyTestHttpServerHandler",new TestHttpServerHandler());
}
}
``` TestHttpServerHandler.java
##
```java
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.net.URI;
/**
* @PackageName : com.rzk.netty.http
* @FileName : TestHttpServerHandler
* @Description : 接收和发送信息
* SimpleChann睿共享elInboundHandler: 是ChannelInboundHandlerAdapter
* HttpObject:客户端和服务端相互通讯的数据被封装成 HttpObject
* @Author : rzk
* @CreateTime : 2021/2/19 18:55
* @Version : 1.0.0
*/
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
//读取客户端数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
//判断msg 是不是 httprequest 请求
if(msg instanceof HttpRequest){
System.out.println("msg 类型 = " + msg.getClass());
System.out.println("客户端地址 "+ ctx.channel().remoteAddress());
//获取到
HttpRequest httpRequest = (HttpRequest) msg;
//获取URL统一资源定位
URI uri = new URI(httpRequest.uri());
//这个url里面就有我们想要的地址
//如果url路径里面有favicon.ico 就不获取
if("/favicon.ico".equals(uri.getPath())){
System.out.println("请求到了 .ico 资源,不做响应");
return;
}
//回复信息给浏览器 [http协议]
ByteBuf content = Unpooled.copiedBuffer("hello ,我是服务器", CharsetUtil.UTF_8);
//构造一个http的 响应 ,即HTTPResponse
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());
//将构建好 response返回
ctx.writeAndFlush(response);
}
}
}
访问http://localhost:8880