netty Demo 实例

来源:互联网 发布:周口网络销售招聘信息 编辑:程序博客网 时间:2024/05/17 02:43

netty写的代理服务器Demo

package com.jiepu.netty2;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;/** * netty写的代理服务器Demo * http://www.oschina.net/code/snippet_573815_50151 */public class CommonServer {public static void main(String[] args) throws Exception {//http://localhost:9999/start(9999);}public static void start(int port) throws InterruptedException {EventLoopGroup bossGroup = new NioEventLoopGroup();NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);workerGroup.setIoRatio(50);try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch)throws Exception {System.out.println("server  start");ch.config().setAutoRead(true);ch.pipeline().addLast(new HttpRequestDecoder());ch.pipeline().addLast(new HttpResponseEncoder());ch.pipeline().addLast(new HttpServerHandler2());}}).option(ChannelOption.SO_BACKLOG, 128) // 流控.childOption(ChannelOption.SO_KEEPALIVE, true);ChannelFuture f = b.bind(port).sync();System.out.println("run");f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}}

package com.jiepu.netty2;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.http.DefaultHttpRequest;import io.netty.handler.codec.http.DefaultLastHttpContent;import io.netty.handler.codec.http.HttpContent;import io.netty.handler.codec.http.HttpMethod;import io.netty.handler.codec.http.HttpResponse;import io.netty.handler.codec.http.HttpVersion;import java.net.URI;/** * 类HttpClientHandler2.java的实现描述:TODO 类实现描述 *  * @author yp 2015年8月10日 上午9:15:46 */public class HttpClientHandler2 extends ChannelHandlerAdapter {String host;String uri;ChannelHandlerContext serverCtx;public HttpClientHandler2(String host, String uri,ChannelHandlerContext serverCtx) {this.host = host;this.uri = uri;this.serverCtx = serverCtx;}@Overridepublic void channelActive(final ChannelHandlerContext ctx) throws Exception {URI uri = new URI(this.uri);DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET, uri.toASCIIString());req.headers().add("Host", this.host);ctx.writeAndFlush(req);}/* * tb2.bdstatic.com/img/search_logo_7835b03.png (non-Javadoc) *  * @see io.netty.channel.ChannelHandlerAdapter#channelRead(io.netty.channel. * ChannelHandlerContext, java.lang.Object) */@Overridepublic void channelRead(ChannelHandlerContext ctx, final Object msg)throws Exception {if (msg instanceof HttpResponse) {serverCtx.writeAndFlush(msg);} else if (msg instanceof DefaultLastHttpContent) {// 最后的消息serverCtx.writeAndFlush(msg);ctx.channel().close();} else if (msg instanceof HttpContent) {serverCtx.writeAndFlush(msg);}}}
package com.jiepu.netty2;/* * Copyright 2015 yp All right reserved. This software is the * confidential and proprietary information of yp ("Confidential * Information"). You shall not disclose such Confidential Information and shall * use it only in accordance with the terms of the license agreement you entered * into with yp . */import io.netty.bootstrap.Bootstrap;import io.netty.buffer.PooledByteBufAllocator;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.http.HttpContent;import io.netty.handler.codec.http.HttpRequest;import io.netty.handler.codec.http.HttpRequestEncoder;import io.netty.handler.codec.http.HttpResponseDecoder; import java.net.InetAddress;/** * 类HttpServerHandler2.java的实现描述:TODO 类实现描述 *  * @author yp 2015年8月10日 上午9:17:17 */public class HttpServerHandler2 extends ChannelHandlerAdapter {     @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {         if (msg instanceof HttpRequest) {            HttpRequest request = (HttpRequest) msg;            //System.out.println(request.toString());                        if (request.getUri().contains("pic1")) {                InetAddress iAddress = InetAddress.getByName("asearch.alicdn.com");                String uri = "/bao/uploaded/i1/189050106579034484/TB28ir7dpXXXXbcXXXXXXXXXXXX_!!17468905-0-saturn_solar.jpg_200x200.jpg_.webp";                Bootstrap b = createBootStrap(ctx, "asearch.alicdn.com", uri);                b.connect(iAddress, 80);            } else {                InetAddress iAddress = InetAddress.getByName("i1.itc.cn");                String uri = "/20150806/31e9_f52bb95f_f509_7bc6_5def_c0e48e908048_1.jpg";                Bootstrap b = createBootStrap(ctx, "i1.itc.cn", uri);                b.connect(iAddress, 80);            }        } else if (msg instanceof HttpContent) {            System.out.println("http content");        }    }     /**     * @param ctx     * @param uri     * @return     */    private Bootstrap createBootStrap(final ChannelHandlerContext ctx, final String host, final String uri) {        Bootstrap b = new Bootstrap();        b.group(ctx.channel().eventLoop());        b.channel(NioSocketChannel.class);        b.option(ChannelOption.SO_KEEPALIVE, true);        b.option(ChannelOption.TCP_NODELAY, true);        b.handler(new ChannelInitializer<SocketChannel>() {            @Override            public void initChannel(SocketChannel ch) throws Exception {                ch.config().setAllocator(new PooledByteBufAllocator());                ch.pipeline().addLast(new HttpRequestEncoder());                ch.pipeline().addLast(new HttpResponseDecoder());                ch.pipeline().addLast(new HttpClientHandler2(host, uri, ctx));            }        });        return b;    }}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.jiepu</groupId><artifactId>netty2</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>netty2</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version><scope>test</scope></dependency><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><!-- netty-all --><version>5.0.0.Alpha1</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.7</source><target>1.7</target></configuration></plugin></plugins></build></project>




0 0