1、BIO、NIO、AIO相关后期补充
。。。。。。
2、Hello Netty
package com.renxiaobo.wechat.demo01;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
/**
* Author:rxb
* Date:2020-06-10 20:44
* Description:客户端发送一个请求,服务端返回hello netty
*/
public class HelloServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("HttpServerCodec", new HttpServerCodec());//netty自己提供的 助手类,当请求到服务端,需要-解码,响应到客户-做编码
pipeline.addLast(new ChildHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8081).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
/***************************************************************
* 这是一个漂亮的分隔符
***************************************************************/
class ChildHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
Channel channel = ctx.channel();
if(msg instanceof HttpRequest && !((HttpRequest) msg).uri().contains("/favicon.ico")){
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);
}
}
}
3、启动项目
启动项目,run -> 浏览器localhost:8081直接访问即可(未过滤localhost:8081/xxxx类似的路径)