1. 程式人生 > >使用netty自行實現簡單的http服務端開發

使用netty自行實現簡單的http服務端開發

瞭解http伺服器工作原理:
http客戶端和伺服器端的互動步驟:
1 client想server傳送http請求
2 server端對http請求進行解析
3 server端向client傳送http響應
4 client對http響應進行解析


使用netty自行實現http服務端開發:
針對http主要就是接收請求  處理請求  返回響應
Netty的api很簡單  建立NioEventLoopGroup,建立ServerBootstrap 不再過多闡述
最主要的就是在初始化channel中的pipeline鏈上新增一系列操作
1 新增 HttpRequestDecoder() http請求訊息解碼器
2 新增 HttpObjectAggregator解碼器  將多個訊息轉換為單一的FullHttpRequest或FullHttpResponse物件
3 新增 HttpResponseEncoder() HTTP響應編碼器,對HTTP響應進行編碼
4 新增 ChunkedWriteHandler的主要作用是支援非同步傳送大的碼流,但不佔用過多的記憶體,防止JAVA記憶體溢位

5 新增  HttpFileServerHandler(DEFAULT_URL)) 自定義的通道處理器,其目的是實現伺服器的業務邏輯 比如檔案伺服器。

針對HttpFileServerHandler的實現 繼承了SimpleChannelInboundHandler

複寫messageReceived  方法體內 主要就是處理get,post請求的處理 等等

具體程式碼如下(附帶註釋)

HttpServer

package httpnetty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;


public class HttpServer {
	private static final String DEFAULT_URL = "/src/";
	public void run(final int port) throws Exception {
		// 內部維護了一組執行緒,每個執行緒負責處理多個Channel上的事件,而一個Channel只對應於一個執行緒,這樣可以迴避多執行緒下的資料同步問題
		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
						protected void initChannel(SocketChannel ch)
								throws Exception {


							// HTTP請求訊息解碼器
							ch.pipeline().addLast("http-decoder",
									new HttpRequestDecoder());


							/*
							 * HttpObjectAggregator解碼器
							 * 將多個訊息轉換為單一的FullHttpRequest或FullHttpResponse物件
							 */
							ch.pipeline().addLast("http-aggregator",
									new HttpObjectAggregator(65536));


							// HTTP響應編碼器,對HTTP響應進行編碼
							ch.pipeline().addLast("http-encoder",
									new HttpResponseEncoder());


							// ChunkedWriteHandler的主要作用是支援非同步傳送大的碼流,但不佔用過多的記憶體,防止JAVA記憶體溢位
							ch.pipeline().addLast("http-chunked",
									new ChunkedWriteHandler());
                           //自定義的通道處理器,其目的是實現檔案伺服器的業務邏輯。
							ch.pipeline().addLast("httpServerHandler",
									new HttpFileServerHandler(DEFAULT_URL));
						}
					});
			//繫結埠  發起非同步連線操作
			ChannelFuture future = b.bind("localhost", port).sync();
			System.out.println("HTTP Server startup.");
			//等待客戶端鏈路關閉
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//優雅退出  釋放NIO執行緒組
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	public static void main(String[] args) throws Exception {
		int port = 8080;
		new HttpServer().run(port);
	}
}

HttpFileServerHandler:

package httpnetty;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import java.util.regex.Pattern;

import javax.activation.MimetypesFileTypeMap;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelProgressiveFuture;
import io.netty.channel.ChannelProgressiveFutureListener;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;

import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.stream.ChunkedFile;
import io.netty.util.CharsetUtil;
public class HttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest>{

    private final String url;
    
    public HttpFileServerHandler(String url) {
        this.url = url;
    }
    
    @Override
    protected void messageReceived(ChannelHandlerContext ctx,
            FullHttpRequest request) throws Exception {
        if(!request.decoderResult().isSuccess())
        {
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        if(request.method() != HttpMethod.GET)
        {
            sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
            return;
        }
        
        final String uri = request.uri();
        final String path = sanitizeUri(uri);
        if(path == null)
        {
            sendError(ctx, HttpResponseStatus.FORBIDDEN);
            return;
        }
        
        File file = new File(path);
        if(file.isHidden() || !file.exists())
        {
            sendError(ctx, HttpResponseStatus.NOT_FOUND);
            return;
        }
        if(file.isDirectory())
        {
            if(uri.endsWith("/"))
            {
                sendListing(ctx, file);
            }else{
                sendRedirect(ctx, uri + "/");
            }
            return;
        }
        if(!file.isFile())
        {
            sendError(ctx, HttpResponseStatus.FORBIDDEN);
            return;
        }
        
        RandomAccessFile randomAccessFile = null;
        try{
            randomAccessFile = new RandomAccessFile(file, "r");
        }catch(FileNotFoundException fnfd){
            sendError(ctx, HttpResponseStatus.NOT_FOUND);
            return;
        }
        
        long fileLength = randomAccessFile.length();
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        HttpHeaderUtil.setContentLength(response, fileLength);
//        setContentLength(response, fileLength);
        setContentTypeHeader(response, file);
        
        
        
        if(HttpHeaderUtil.isKeepAlive(request)){
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        
        ctx.write(response);
        ChannelFuture sendFileFuture = null;
        sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), ctx.newProgressivePromise());
        sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
            
            @Override
            public void operationComplete(ChannelProgressiveFuture future)
                    throws Exception {
                System.out.println("Transfer complete.");
                
            }
            
            @Override
            public void operationProgressed(ChannelProgressiveFuture future,
                    long progress, long total) throws Exception {
                if(total < 0)
                    System.err.println("Transfer progress: " + progress);
                else
                    System.err.println("Transfer progress: " + progress + "/" + total);
            }
        });
        
        ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if(!HttpHeaderUtil.isKeepAlive(request))
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        if(ctx.channel().isActive())
            sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
    
    private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");
    private String sanitizeUri(String uri){
        try{
            uri = URLDecoder.decode(uri, "UTF-8");
        }catch(UnsupportedEncodingException e){
            try{
                uri = URLDecoder.decode(uri, "ISO-8859-1");
            }catch(UnsupportedEncodingException e1){
                throw new Error();
            }
        }
        
        if(!uri.startsWith(url))
            return null;
        if(!uri.startsWith("/"))
            return null;
        
        uri = uri.replace('/', File.separatorChar);
        if(uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.startsWith(".") || uri.endsWith(".") 
                || INSECURE_URI.matcher(uri).matches()){
            return null;
        }
        return System.getProperty("user.dir") + File.separator + uri;
    }
    
    private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");
    
    private static void sendListing(ChannelHandlerContext ctx, File dir){
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
//        response.headers().set("CONNECT_TYPE", "text/html;charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
        
        String dirPath = dir.getPath();
        StringBuilder buf = new StringBuilder();
        
        buf.append("<!DOCTYPE html>\r\n");
        buf.append("<html><head><title>");
        buf.append(dirPath);
        buf.append("目錄:");
        buf.append("</title></head><body>\r\n");
        
        buf.append("<h3>");
        buf.append(dirPath).append(" 目錄:");
        buf.append("</h3>\r\n");
        buf.append("<ul>");
        buf.append("<li>連結:<a href=\" ../\")..</a></li>\r\n");
        for (File f : dir.listFiles()) {
            if(f.isHidden() || !f.canRead()) {
                continue;
            }
            String name = f.getName();
            if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
                continue;
            }
            
            buf.append("<li>連結:<a href=\"");
            buf.append(name);
            buf.append("\">");
            buf.append(name);
            buf.append("</a></li>\r\n");
        }
        
        buf.append("</ul></body></html>\r\n");
        
        ByteBuf buffer = Unpooled.copiedBuffer(buf,CharsetUtil.UTF_8);  
        response.content().writeBytes(buffer);  
        buffer.release();  
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); 
    }
    
    
    private static void sendRedirect(ChannelHandlerContext ctx, String newUri){
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
//        response.headers().set("LOCATIN", newUri);
        response.headers().set(HttpHeaderNames.LOCATION, newUri);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status){
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, 
                Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
    private static void setContentTypeHeader(HttpResponse response, File file){
        MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(file.getPath()));
    }
}



相關推薦

使用netty自行實現簡單http服務開發

瞭解http伺服器工作原理:http客戶端和伺服器端的互動步驟:1 client想server傳送http請求2 server端對http請求進行解析3 server端向client傳送http響應4 client對http響應進行解析使用netty自行實現http服務端開發

Python實現簡單HTTP服務器(一)

recv ati listen bind ESS 內容 text code 讀取內容 一.返回固定內容 # coding:utf-8 import socket from multiprocessing import Process def handle_clien

AgileEAS.NET SOA 中介軟體平臺.Net Socket通訊框架-簡單例子-實現簡單服務客戶訊息應答

一、AgileEAS.NET SOA中介軟體Socket/Tcp框架介紹 AgileEAS.NET SOA中介軟體Socket/Tcp框架是一套Socket通訊的訊息中介軟體: 二、簡單例子-實現簡單的伺服器客戶段訊息應答      我們接下來實現一個簡單的例子,例子的場景非常的簡單,客戶端向服

基於netty框架實現的TCP服務程式

工程目錄結構 程式碼:NioServer main類 import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.Channel

Java中利用socket實現簡單服務與客戶的通訊(入門級)

Java程式設計中,要想要使用網路通訊,就離不開Socket程式設計,在此對socket進行簡單的介紹。首先宣告,這是一個入門級的介紹,僅僅簡單的實現了客戶端向服務端傳送資料,服務端正常的接收資料,當接收到特定的資料時,服務端和客戶端都關閉,一個服務端對應一個客戶端,不涉及

Java中利用socket實現簡單服務與客戶的通訊(基礎級)

在上一篇文章中,簡單的介紹了java中入門級的socket程式設計,簡單的實現了客戶端像伺服器端傳送資料,伺服器端將資料接收並顯示在控制檯,沒有涉及多執行緒。上一篇文章的連結:Java中利用socket實現簡單的服務端與客戶端的通訊(入門級) 這次,我們將上一節中的程式碼進

netty實現一個簡單服務和客戶通訊

netty java Nio網路通訊框架,能接收TCP,http,webSocket,UDPelk包括:logStash,Elasticsearch,KibanaLogStash:tcp監聽netty伺服器傳送的資訊,並把訊息處理好後轉發給ESElasticsearch:接受

JPush簡單Java服務案例實現

服務端 開發者 comm platform die spa message else 獲取數據 一、激光推送準備工作 1、註冊極光推送開發者賬號,創建應用: 2、完成推送設置,填寫應用名提交生成安裝包: 3、掃碼安裝簡單的測試apk,查看應用信息會有AppKey和Mas

Netty實現簡單UDP服務

rec nal req 參考 syn group out equal 文件 本文參考《Netty權威指南》 文件列表: ├── ChineseProverbClientHandler.java ├── ChineseProverbClient.java ├── Chine

Netty實現簡單HTTP代理伺服器

自上次使用Openresty+Lua+Nginx的來加速自己的網站,用上了比較時髦的技術,感覺算是讓自己的網站響應速度達到極限了,直到看到了Netty,公司就是打算用Netty來替代Openresty這一套,所以,自己也學了好久,琢磨了好一趟才知道怎麼用,現在用來寫一套HTTP代理伺服器吧,之後再測試一下效能

node服務開發中express路由和http路由總結

express.router() // 第一引入express 並且建立express例項 var express = require('express')var router = express.Router(); // 第二部使用express路由方法: router.METHOD(PAT

使用Go語言實現http服務指定路徑的檔案.

package main import ( "io" "net/http" ) func main() { http.HandleFunc("/", router) http.Listen

用多執行緒實現多使用者同時收發的簡單socket服務

簡單的socket程式碼和多執行緒練習用socket服務端和多執行緒實現可以連線多個客戶端並同時收發的功能。這裡要用到socket 和 threading所以,記得:import socket, threading一、建立socket服務端首先,按正常操作,建立一個socke

用libevent開發一個http服務,附帶一個curl http客戶

對http互動較為陌生,所以最近寫了兩個小demo,一個http server 和一個http client,對於http server,很多人推薦使用libevent。http server:#include <stdlib.h> #include <st

HTTP服務介面模擬工具-HttpServerMockTool 1 工具功能介紹 這個工具可以通過簡單的配置達到快速模擬第三方HTTP服務介面的作用,替代以前要手寫servlet程式碼再放到to

HTTP服務端介面模擬工具-HttpServerMockTool 1 工具功能介紹 這個工具可以通過簡單的配置達到快速模擬第三方HTTP服務端介面的作用,替代以前要手寫servlet程式碼再放到tomcat下的過程。 2 工具使用指南 使用前請仔細閱讀工具使用指南

netty的websocket服務開發

前兩篇文章分析了node.js版本的socket.io的服務端與客戶端的程式碼,其實他們socket.io就是在websocket的基礎上進一步做了一層封裝,添加了一些心跳,重連線。。。 這篇文章就先來看看在netty中是如何建立websocket服務端的吧,先來回顧一下w

boost的asio實現簡單的客戶服務

客戶端: //客戶端 #include "stdafx.h" #include<boost/asio/io_service.hpp> #include<boost/asio/ip/tcp.hpp> #include<

C++ 簡單Socket服務程式碼實現

程式碼如下:// Server.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include <winsock2.h> #pragma comment(lib,"Ws2_32.lib") int _tmain(in

記一次學習配置叢集eureka,註冊生成者、消費實現簡單服務呼叫

總結一次基於SpringCloud,Greenwich.SR2版本部署叢集eureka,註冊生產者、消費者並進行簡單呼叫的流程。

曹工雜談:花了兩天時間,寫了一個netty實現http客戶,支援同步轉非同步和連線池(1)--核心邏輯講解

# 背景 先說下寫這個的目的,其實是好奇,dubbo是怎麼實現同步轉非同步的,然後瞭解到,其依賴了請求中攜帶的請求id來完成這個連線複用;然後我又發現,redisson這個redis客戶端,底層也是用的netty,那就比較好奇了:netty是非同步的,上層是同步的,要拿結果的,同時呢,redis協議也不可能