netty 基于 http1.0 开发

简介:     package com.netty.core; import java.security.cert.CertificateException; import javax.

 

 

package com.netty.core;

import java.security.cert.CertificateException;

import javax.net.ssl.SSLException;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import com.netty.util.NettyPropertiesUtil;

public class NettyServer implements InitializingBean {

	Logger logger = Logger.getLogger(NettyServer.class);

	public boolean isSSL = true;
	public int port = 8443;
	public int threadSize = 1;
	public int connnecttimeout = 10000;
	public int sotimeout = 10000;

	public void init() {
		isSSL = Integer
				.parseInt(NettyPropertiesUtil.getProperty("netty.isSSL")) == 1 ? true
				: false;
		port = Integer.parseInt(NettyPropertiesUtil.getProperty("netty.port"));
		threadSize = Integer.parseInt(NettyPropertiesUtil
				.getProperty("netty.nioeventloopgroup.size"));
		connnecttimeout = Integer.parseInt(NettyPropertiesUtil
				.getProperty("netty.serverbootstrap.connnecttimeout"));
		sotimeout = Integer.parseInt(NettyPropertiesUtil
				.getProperty("netty.serverbootstrap.sotimeout"));
	}

	@SuppressWarnings({ "deprecation" })
	public void start() throws CertificateException, SSLException,
			InterruptedException {
		logger.info("netty server  start");
		final SslContext sslCtx;
		if (isSSL) {
			SelfSignedCertificate ssc = new SelfSignedCertificate();
			sslCtx = SslContext.newServerContext(ssc.certificate(),
					ssc.privateKey());
		} else {
			sslCtx = null;
		}

		EventLoopGroup bossGroup = new NioEventLoopGroup(threadSize);
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.option(ChannelOption.SO_BACKLOG, 1024);
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))
					.childHandler(new NettyServerInitializer(sslCtx));
			b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connnecttimeout);
			b.option(ChannelOption.SO_TIMEOUT, sotimeout);

			Channel ch = b.bind(port).sync().channel();
			logger.info("netty server end");
			ch.closeFuture().sync();
			logger.info("netty end ");
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		try {
			logger.info(" netty conf init start");
			init();
			logger.info(" netty conf init end");
		} catch (Exception e) {
			logger.info(" netty conf init fail");
			e.printStackTrace();
		}
	}

}

 

package com.netty.core;
 
import org.apache.log4j.Logger;
 

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
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.HttpHeaders;
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.HttpHeaders.Names; 

public class NettyServerHandler extends ChannelInboundHandlerAdapter {
	
	Logger logger = Logger.getLogger(NettyServerHandler.class);
	 
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof HttpRequest){
			HttpRequest req = (HttpRequest) msg;
			logger.info("RECV MSG: "+req.getUri());
			if(HttpHeaders.is100ContinueExpected(req)){
				ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
			}
			String resp="ok";
			FullHttpResponse  response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(resp.getBytes()));
			response.headers().set(Names.CONTENT_TYPE, "text/html; charset=utf-8");
			response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
			ctx.write(response).addListener(ChannelFutureListener.CLOSE);
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
	

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}
	
}

 

package com.netty.core;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslContext;

public class NettyServerInitializer  extends ChannelInitializer<SocketChannel> {

private final SslContext sslCtx;
    
    public NettyServerInitializer() {
    	sslCtx=null;
    }
    
    public NettyServerInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        if (null!=sslCtx) {
            p.addLast(sslCtx.newHandler(ch.alloc()));
        }
        p.addLast(new HttpServerCodec());
        //完整参数封装
        p.addLast("aggregator", new HttpObjectAggregator(1048576));  
        p.addLast(new NettyServerHandler());
    }


	
}

 

package test.netty;

import java.net.URI;

import org.junit.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 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.HttpResponse;
 
public class NettyClientTest {

	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>() {
                @Override
                public 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:8443");
            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();
        }

    }
 
	@Test
	public void Test(){
		try{ 
			NettyClientTest client = new NettyClientTest();
	        client.connect("127.0.0.1", 8443);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

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();
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

目录
相关文章
|
6月前
Netty实战: HTTP文件列表服务器
Netty实战: HTTP文件列表服务器
70 0
|
6月前
|
XML 存储 网络协议
kettle开发篇-Http client
kettle开发篇-Http client
712 0
|
6月前
|
Java Unix Linux
【Netty技术专题】「原理分析系列」Netty强大特性之Native transports扩展开发实战
当涉及到网络通信和高性能的Java应用程序时,Netty是一个强大的框架。它提供了许多功能和组件,其中之一是JNI传输。JNI传输是Netty的一个特性,它为特定平台提供了高效的网络传输。 在本文中,我们将深入探讨Netty提供的特定平台的JNI传输功能,分析其优势和适用场景。我们将介绍每个特定平台的JNI传输,并讨论其性能、可靠性和可扩展性。通过了解这些特定平台的JNI传输,您将能够更好地选择和配置适合您应用程序需求的网络传输方式,以实现最佳的性能和可靠性。
145 7
【Netty技术专题】「原理分析系列」Netty强大特性之Native transports扩展开发实战
|
1月前
|
Rust 前端开发 API
Tauri 开发实践 — Tauri HTTP 请求开发
本文介绍了如何在 Tauri 中发起 HTTP 请求。首先通过安装 Tauri 生态中的工具包并配置 `tauri.conf.json` 文件来允许特定域名的 HTTP 通信。接着封装了一个简单的 HTTP 客户端类,并在页面中使用该客户端实现 GET 和 POST 请求。最后提供了完整的源码地址以供参考。此功能使得桌面应用能够与远程服务器进行交互,增强了应用的实用性。
88 1
Tauri 开发实践 — Tauri HTTP 请求开发
|
1月前
使用Netty实现文件传输的HTTP服务器和客户端
本文通过详细的代码示例,展示了如何使用Netty框架实现一个文件传输的HTTP服务器和客户端,包括服务端的文件处理和客户端的文件请求与接收。
44 1
使用Netty实现文件传输的HTTP服务器和客户端
|
3月前
|
API 开发者
Netty运行原理问题之Netty实现低开发门槛的问题如何解决
Netty运行原理问题之Netty实现低开发门槛的问题如何解决
|
4月前
|
运维 Serverless API
Serverless 应用引擎使用问题之如何开发HTTP服务
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
|
6月前
|
JSON Java API
Android 深入Http(5)从Retrofit源码来看Http,最新Android开发面试解答
Android 深入Http(5)从Retrofit源码来看Http,最新Android开发面试解答
|
6月前
|
缓存 前端开发 JavaScript
React和Next.js开发常见的HTTP请求方法
React和Next.js开发常见的HTTP请求方法
114 0
|
6月前
|
网络协议 安全 Java
理解HTTP协议:Java Web开发的基础
【4月更文挑战第3天】本文介绍了HTTP协议的基础知识,包括其无状态、应用层协议的特性,基于请求/响应的工作模式,以及TCP连接、HTTP请求和响应的流程。HTTP方法如GET、POST、PUT等用于不同操作,状态码则表示请求结果。在Java Web开发中,理解HTTP有助于设计RESTful API、管理状态、确保安全性、优化性能和处理错误。HTTP协议的深入理解对构建高效、健壮和安全的Web应用至关重要。
71 3

热门文章

最新文章

下一篇
无影云桌面