基于netty构建一个http服务

客户端代码package com.huanfeng.test;import JAVA.io.BufferedReader;import java.io.InputStreamReader;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;public class Test11 {public static void main(String[] args) {int num=100;for (int i=0;i<num;i++){new Thread(new Runnable() {@Overridepublic void run() {String s=Test11.sendGet("http://localhost:8082");System.out.println(s);}}).start();}}public static String sendGet(String url) {String result = "";BufferedReader in = null;try {String urlNameString = url;URL realUrl = new URL(urlNameString);// 打开和URL之间的连接URLConnection connection = realUrl.openConnection();// 设置通用的请求属性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; windows NT 5.1;SV1)");// 建立实际的连接connection.connect();// 获取所有响应头字段Map<String, List<String>> map = connection.getHeaderFields();// 遍历所有的响应头字段for (String key : map.keySet()) {System.out.println(key + "--->" + map.get(key));}// 定义 BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("发送GET请求出现异常!" + e);e.printStackTrace();}// 使用finally块来关闭输入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}}服务端代码package com.huanfeng.test;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;public class Test10 {public static void main(String[] args) throws Exception{EventLoopGroup bossGroup=new NioEventLoopGroup(1);EventLoopGroup workerGroup=new NioEventLoopGroup();try{ServerBootstrap serverBootstrap=new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new TestServerInitializer());ChannelFuture channelFuture =serverBootstrap.bind(8082).sync();channelFuture.channel().closeFuture().sync();}finally{bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}【基于netty构建一个http服务】package com.huanfeng.test;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 kotlin.random.Random;//HttpObject客户端和服务段相互通信的数据封装成HttpObjectpublic class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {if(msg instanceof HttpRequest){System.out.println("msg 类型"+msg.getClass());System.out.println("客户端地址"+ctx.channel().remoteAddress());//回复信息给浏览器ByteBuf content= Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);//构建一个http响应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);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}}package com.huanfeng.test;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 TestServerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//向管道加入处理器//得到管道ChannelPipeline pipeline = ch.pipeline();//加入一个netty提供的httpServerCodec//编解码器//http的编解码器pipeline.addLast("MyHttpServerCode",new HttpServerCodec());//添加自定义的处理器pipeline.addLast("MyTestHttpServerHandler",new TestHttpServerHandler());}}



    推荐阅读