BusiHandler
public class BusiHandler extends ChannelInboundHandlerAdapter { /** * 发送的返回值 * @param ctx 返回 * @param context 消息 * @param status 状态 */ private void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1,status, Unpooled.copiedBuffer(context,CharsetUtil.UTF_8) ); response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String result=""; FullHttpRequest httpRequest = (FullHttpRequest)msg; System.out.println(httpRequest.headers()); try{ //获取路径 String path=httpRequest.uri(); //获取body String body = httpRequest.content().toString(CharsetUtil.UTF_8); //获取请求方法 HttpMethod method=httpRequest.method(); System.out.println("接收到:"+method+" 请求"); //如果不是这个路径,就直接返回错误 if(!"/test".equalsIgnoreCase(path)){ result="非法请求!"+path; send(ctx,result,HttpResponseStatus.BAD_REQUEST); return; } //如果是GET请求 if(HttpMethod.GET.equals(method)){ //接受到的消息,做业务逻辑处理... System.out.println("body:"+body); result="GET请求,应答:"+RespConstant.getNews(); send(ctx,result,HttpResponseStatus.OK); return; } //如果是其他类型请求,如post if(HttpMethod.POST.equals(method)){ //接受到的消息,做业务逻辑处理... //.... return; } }catch(Exception e){ System.out.println("处理请求失败!"); e.printStackTrace(); }finally{ //释放请求 httpRequest.release(); } } /* * 建立连接时,返回消息 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress()); }}
HttpServer
public class HttpServer { public static final int port = 6789; //设置服务端端口 private static EventLoopGroup group = new NioEventLoopGroup(); // 通过nio方式来接收连接和处理连接 private static ServerBootstrap b = new ServerBootstrap(); private static final boolean SSL = false;/*是否开启SSL模式*/ /** * Netty创建全部都是实现自AbstractBootstrap。 * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 **/ public static void main(String[] args) throws Exception { final SslContext sslCtx; if(SSL){ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); }else{ sslCtx = null; } try { b.group(group); b.channel(NioServerSocketChannel.class); b.childHandler(new ServerHandlerInit(sslCtx)); //设置过滤器 // 服务器绑定端口监听 ChannelFuture f = b.bind(port).sync(); System.out.println("服务端启动成功,端口是:"+port); // 监听服务器关闭监听 f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); //关闭EventLoopGroup,释放掉所有资源包括创建的线程 } }}
RespConstant
public class RespConstant { private static final String[] NEWS = { "她那时候还太年轻,不知道所有命运赠送的礼物,早已在暗中标好了价格。——斯蒂芬·茨威格《断头皇后》", "这是一个最好的时代,也是一个最坏的时代;这是一个智慧的年代,这是一个愚蠢的年代;\n" + "这是一个信任的时期,这是一个怀疑的时期;这是一个光明的季节,这是一个黑暗的季节;\n" + "这是希望之春,这是失望之冬;人们面前应有尽有,人们面前一无所有;\n" + "人们正踏上天堂之路,人们正走向地狱之门。 —— 狄更斯《双城记》", }; private static final Random R = new Random(); public static String getNews(){ return NEWS[R.nextInt(NEWS.length)]; }}
ServerHandlerInit
public class ServerHandlerInit extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; public ServerHandlerInit(SslContext sslCtx) { this.sslCtx = sslCtx; } @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline ph = ch.pipeline(); if(sslCtx!=null){ ph.addLast(sslCtx.newHandler(ch.alloc())); } /*把应答报文 编码*/ ph.addLast("encoder",new HttpResponseEncoder()); /*把请求报文 解码*/ ph.addLast("decoder",new HttpRequestDecoder()); /*聚合http为一个完整的报文*/ ph.addLast("aggregator",new HttpObjectAggregator(10*1024*1024)); /*把应答报文 压缩,非必要*/ ph.addLast("compressor",new HttpContentCompressor()); ph.addLast(new BusiHandler()); }}