netty It can also be used as a small one http Server usage .

 package com.ming.netty.http.httpserver;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import; public class HttpServer { public static void main(String[] args) {
new HttpServer().run("", 8500);
} public void run(String addr,int port){
NioEventLoopGroup boosGroup=new NioEventLoopGroup();
NioEventLoopGroup workGroup=new NioEventLoopGroup();
try {
ServerBootstrap bootstrap=new ServerBootstrap();, workGroup);;
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536));// Define the amount of buffered data
ch.pipeline().addLast("encoder", new HttpResponseDecoder());
ch.pipeline().addLast("chunkedWriter", new ChunkedWriteHandler());
ch.pipeline().addLast("deflater", new HttpContentCompressor());// Compression
ch.pipeline().addLast("handler", new HttpServerHandler());
} });
ChannelFuture f=bootstrap.bind(new InetSocketAddress(addr, port)).sync();
System.out.println(" Start the server :";
// Wait, the server listening port is closed;
} catch (Exception e) {
} }
 package com.ming.netty.http.httpserver;
import java.nio.ByteBuffer;
import java.util.Map; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
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.HttpMessage;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.CharsetUtil; public class HttpServerHandler extends SimpleChannelInboundHandler<Object> { private HttpRequest request; private ByteBuf buffer_body = UnpooledByteBufAllocator.DEFAULT.buffer(); private StringBuffer sb_debug = new StringBuffer(); @Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
DefaultFullHttpRequest request=(DefaultFullHttpRequest)msg; System.out.println(" Start the server :"+request.getMethod()+request.getUri());
try {
if ((msg instanceof HttpMessage) && HttpHeaders.is100ContinueExpected((HttpMessage)msg)) {
ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
if (msg instanceof HttpRequest) {
this.request = (HttpRequest)msg;
sb_debug.append("\n>> HTTP REQUEST -----------\n");
.append(" ").append(this.request.getMethod().name())
.append(" ").append(this.request.getUri());
HttpHeaders headers = this.request.headers();
if (!headers.isEmpty()) {
for (Map.Entry<String, String> header : headers) {
sb_debug.append(header.getKey()).append(": ").append(header.getValue()).append("\n");
} else if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
ByteBuf thisContent = content.content();
if (thisContent.isReadable()) {
if (msg instanceof LastHttpContent) {
LastHttpContent trailer = (LastHttpContent) msg;
if (!trailer.trailingHeaders().isEmpty()) {
for (String name : trailer.trailingHeaders().names()) {
for (String value : trailer.trailingHeaders().getAll(name)) {
sb_debug.append("\n<< HTTP REQUEST -----------");
} catch (Exception e) {
} finally {
FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
String str="hello,my netty httpServer!";
StringBuilder buf=new StringBuilder();
buf.append("<!DOCTYPE html><head></head><body>").append(str).append("</body></html>");
ByteBuf buffer=Unpooled.copiedBuffer(buf,CharsetUtil.UTF_8);
response.headers().set("Content-Type", "text/html; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
} }

netty httpserver More articles about

  1. ( Advanced Netty Multi protocol development and Application ) Chapter ten -Http Protocol development application ( be based on Netty Of HttpServer and HttpClient Simple implementation of )

    1.HttpServer package nettyHttpTest; import io.netty.bootstrap.ServerBootstrap; import io.netty.chann ...

  2. Netty introduction 2 And ---- Manual build HttpServer

    In the last chapter we met netty, He has three advantages : High concurrency , Fast transmission , Package it . In this chapter we use Netty Building a HttpServer, Learn from actual development netty Some features and concepts of framework . netty.png know ...

  3. Mina、Netty、Twisted Learn together ( 8、 ... and ):HTTP The server

    HTTP Protocol should be the most used application layer protocol at present , To open a website with a browser is to use HTTP Protocol for data transmission . HTTP The agreement is also based on TCP agreement , So there are also servers and clients .HTTP The client is usually a browser , Of course, it could be ...

  4. be based on Netty4 Of HttpServer and HttpClient Simple implementation of

    Netty The home page of : The use of Netty Version of :netty-4.0.23.Final.tar.bz2 ‐ 15-Aug-2014 (Stable, Re ...

  5. Netty In Action China Version - Chapter two : First of all Netty Program

    This chapter is an introduction. get Netty4 Latest version number Set up the execution environment , To build and execute netty Program Create one based on Netty Of server and client Intercept and handle exceptions Prepare and execute Nettyserver and client Ben ...

  6. netty Advanced (3)-HTTP Protocol development

    One .HTTP Protocol Brief Application layer protocol http, So far, it has been http2.0 了 , It has the following characteristics : (1) CS Protocol of pattern (2) Simple - Just services URL, Carry the necessary request parameters or message body (3) flexible - ren ...

  7. 【netty This matter 】ByteBuf The usage mode of

    Heap Buffer Most commonly used ByteBuf The pattern is to store data in JVM In the heap space of . This pattern is called a support array (backing array), It can provide fast allocation and release without using pooling . Direct buffer direct ...

  8. netty Simple application example of

    One . Simple chat room program public class ChatClient { public static void main(String[] args) throws InterruptedExcept ...

  9. vertx Of HttpServer modular

    Start HttpServer /** * start-up HttpServer * multi instances use synchronized Prevent thread safety issues * addHandlers The method is acto ...

Random recommendation

  1. Windows Server 2012 Virtual reality : The Internet ( One )

    Virtualization's abstraction for computing , You may be relatively familiar with , Maybe all of them are used in stand-alone, such as Virtual PC perhaps Virtual Box Experience . The first impression of using these virtualization software is our CPU You can run multiple different operating systems at the same time , And its ...

  2. java Read properties Profile information

    One .Java Properties class Java There is a more important class in Properties(Java.util.Properties), Mainly used to read Java Configuration file for , Each language has its own supported configuration file , To configure ...

  3. Linux The partition of (1)

    Partition naming : 1.Linux The partition name under is different from windows Under the name of , For hard disks such as IDE The hard disk is similar to /dev/hdxy The way to name , among hd Indicates the device type of the partition , Such as IDE Hard disk ,x Represents the number of the hard disk (a For the basic main disk ...

  4. utilize Cydia Substrate Conduct Android HOOK( Two )

    In the front about Substrate We have talked about the use of Substrate hook java Code , Now let's talk about how to use it hook native Code .hook native Code we need to write Substrate ...

  5. C code -1

    Two key points , One is to understand C grammar , The other is business knowledge , That is, it can decompose the problem Byte order test program Different cpu The byte order on the platform is usually different , Here's a simple C Program , It can test byte order on different platforms . Network byte order is big end byte order . ...

  6. ViewState compression technique

    ViewState Use , We can say it's both love and hate , One of its features is to save the state of the page , For a display page , We can use it directly in the page file EnableViewState="false" ...

  7. jquery easyUI Date formatting ,DateBox Only show year

    jquery easyUI Date formatting ,DateBox Only show year >>>>>>>>>>>>>>>>> ...

  8. solve ERROR 2006 (HY000): MySQL server has gone away

    Just moved blog from Baidu cloud to Tencent cloud , I found a few articles missing . I was importing dump Data time , I once found out that mysql Tips : ERROR 2006 (HY000): MySQL server has gone away N ...

  9. iOS Medium base64 encryption

    #import <UIKit/UIKit.h> @interface Base64String : NSObject + (NSString *)base64String:(NSStrin ...

  10. ASP.Net Mvc Implement customization User Identity User identification system (2)

    In the last blog post, we have realized how to use custom attributes on the page, which is shown in the last blog post @this.U, Today we'll take a closer look at user customization User Identity; Realize the idea : By studying Microsoft's own identity The routine , We can send ...