JAVA 网络编程(7) Netty 处理Http协议 示例
来源:互联网 发布:学生与老师睡觉知乎 编辑:程序博客网 时间:2024/06/06 18:26
maven中使用netty的版本为:
<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.4.Final</version></dependency>
示例代码:
import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; 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.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder;import util.LogCore; public class HttpServer {public void start(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码 ch.pipeline().addLast(new HttpResponseEncoder()); // server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码 ch.pipeline().addLast(new HttpRequestDecoder()); ch.pipeline().addLast(new HttpServerInboundHandler()); } }).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { HttpServer server = new HttpServer(); LogCore.BASE.info("Http Server listening on 8844 ..."); server.start(8844); }}
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;import static io.netty.handler.codec.http.HttpResponseStatus.OK;import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.handler.codec.http.DefaultFullHttpResponse;import io.netty.handler.codec.http.FullHttpResponse;import io.netty.handler.codec.http.HttpContent;import io.netty.handler.codec.http.HttpHeaders;import io.netty.handler.codec.http.HttpHeaders.Values;import io.netty.handler.codec.http.HttpRequest;import util.LogCore;public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {private HttpRequest request;@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {if (msg instanceof HttpRequest) {request = (HttpRequest) msg;String uri = request.getUri();System.out.println("Uri:" + uri);}if (msg instanceof HttpContent) {HttpContent content = (HttpContent) msg;ByteBuf buf = content.content();System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));buf.release();String res = "I am OK";FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,Unpooled.wrappedBuffer(res.getBytes("UTF-8")));response.headers().set(CONTENT_TYPE, "text/plain");response.headers().set(CONTENT_LENGTH, response.content().readableBytes());if (HttpHeaders.isKeepAlive(request)) {response.headers().set(CONNECTION, Values.KEEP_ALIVE);}ctx.write(response);ctx.flush();}}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {LogCore.BASE.error(cause.getMessage());ctx.close();}}
import java.net.URI;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.http.DefaultFullHttpRequest;import io.netty.handler.codec.http.HttpHeaders;import io.netty.handler.codec.http.HttpMethod;import io.netty.handler.codec.http.HttpRequestEncoder;import io.netty.handler.codec.http.HttpResponseDecoder;import io.netty.handler.codec.http.HttpVersion;import util.LogCore;public class HttpClient {public void connect(String host, int port) throws Exception {EventLoopGroup workerGroup = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(workerGroup);b.channel(NioSocketChannel.class);b.option(ChannelOption.SO_KEEPALIVE, true);b.handler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) throws Exception {// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码ch.pipeline().addLast(new HttpResponseDecoder());// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码ch.pipeline().addLast(new HttpRequestEncoder());ch.pipeline().addLast(new HttpClientInboundHandler());}});// Start the client.ChannelFuture f = b.connect(host, port).sync();URI uri = new URI("http://127.0.0.1:8844");String msg = "Are you ok?";DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));// 构建http请求request.headers().set(HttpHeaders.Names.HOST, host);request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());// 发送http请求f.channel().write(request);f.channel().flush();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception {HttpClient client = new HttpClient();client.connect("127.0.0.1", 8844);LogCore.BASE.info("start!!!!");}}
import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.handler.codec.http.HttpContent;import io.netty.handler.codec.http.HttpHeaders;import io.netty.handler.codec.http.HttpResponse;public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {if (msg instanceof HttpResponse) {HttpResponse response = (HttpResponse) msg;System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));}if (msg instanceof HttpContent) {HttpContent content = (HttpContent) msg;ByteBuf buf = content.content();System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));buf.release();}}}
0 0
- JAVA 网络编程(7) Netty 处理Http协议 示例
- JAVA 网络编程(6) Netty TCP 示例
- java 网络编程【10】 HTTP协议详解
- Java中基于HTTP协议网络编程
- Java中基于HTTP协议网络编程
- Java中基于HTTP协议网络编程
- JAVA 网络编程(3) SOCKET 非阻塞NIO 处理HTTP请求示例
- HTTP 协议网络编程
- Netty学习-Java网络编程
- 网络编程基础-http协议
- ios网络编程协议---http
- 网络编程02---HTTP协议
- 网络编程---http协议 ---- 陈洪鑫
- 网络编程---HTTP协议加强
- Java网络编程示例
- Java网络编程(20):HTTP协议简介
- java网络编程(3):HTTP协议调用SOAP
- Java网络编程——第六章 Http协议
- Android studio 主题、字体大小设置
- 307. Range Sum Query - Mutable
- ARM内核中寄存器的浅见
- POJ 2584
- Linux电源管理(8)_Wakeup count功能
- JAVA 网络编程(7) Netty 处理Http协议 示例
- ZIGBEE加密,NV_RESTORE
- okhttp框架中如何设置post请求的编码格式
- 搭建PHP+Apahce+window7环境,和Cannot load c:/php/php5apache2_4.dll into server问题的解决
- bzoj1085: [SCOI2005]骑士精神
- JAVA中public private protected和默认的区别
- C语言基本教程 第12课:文件输入输出(IO)
- akka应用背景介绍
- Android多线程消息处理机制 HandlerThread案例分析