Based on the simple implementation of Netty4 HttpServer and HttpClient, netty4httpserver

Source: Internet
Author: User

Based on the simple implementation of Netty4 HttpServer and HttpClient, netty4httpserver

Netty home page: http://netty.io/index.html

The version of Netty used:Netty-4.0.23.Final.tar.bz2 -15-Aug-2014 (Stable, Recommended)

Implement a simple Http request and response process:

1. The Client sends an http request to the Server.

2. The Server parses the http request.

3. the Server sends an http Response to the client.

4. The Client parses the http response.

Http Server:

Package com. netty. test; import org. apache. commons. logging. log; import org. apache. commons. logging. logFactory; 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; public class HttpServer {private static Log log = LogFactory. getLog (HttpServer. class); 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 {// the server sends httpResponse, so use HttpResponseEncoder to encode ch. pipeline (). addLast (new HttpResponseEncoder (); // The server receives httpRequest, so use HttpRequestDecoder to decode 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 (); log.info ("Http Server listening on 8844... "); server. start (8844 );}}

HttpServerInboundHandler in response to the request:

package com.netty.test;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 org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;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;public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {    private static Log log = LogFactory.getLog(HttpServerInboundHandler.class);    private HttpRequest request;    @Override    public 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(); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { log.error(cause.getMessage()); ctx.close(); }}

Http Client:

Package com. netty. test; 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 java.net. URI; public class HttpClient {public void connect (String host, int port) throws limit t Ion {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> () {@ Override public void initChannel (SocketChannel ch) throws Exception {// The client receives the httpResponse response, so use HttpResponseDecoder to decode the ch. pipeline (). addLast (ne W HttpResponseDecoder (); // the client sends httprequest, so use HttpRequestEncoder to encode 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"); // construct an 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 (); // send the http request 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 );}}

HttpClientInboundHandler that processes the Server response:

package com.netty.test;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 {    @Override    public 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();        }    }}

Log4j Configuration:

# Root logger option
Log4j. rootLogger = INFO, stdout, file

# Direct log messages to stdout
Log4j. appender. stdout = org. apache. log4j. leleappender
Log4j. appender. stdout. Target = System. out
Log4j. appender. stdout. layout = org. apache. log4j. PatternLayout
Log4j. appender. stdout. layout. ConversionPattern = % d {ABSOLUTE} % 5 p % c {1}: % L-% m % n

Log4j. appender. file = org. apache. log4j. DailyRollingFileAppender
Log4j. appender. file. File = logs/log. log
Log4j. appender. file. Append = true
Log4j. appender. file. Threshold = INFO
Log4j. appender. file. layout = org. apache. log4j. PatternLayout
Log4j. appender. file. layout. conversionPattern = %-d {yyyy-MM-dd HH: mm: ss} % 5 p % c {1 }:% L-% m % n

 


What is $ _ SERVER ["HTTP_CLIENT_IP"] in php?

The IP address of the client and the computer where the browser is located.

A program that sends data packets through the Http protocol between the client and the server must use Http Communication. socket is not allowed.

This advertisement is really disgusting.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.