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類似的路徑)