Proxy server example

iwayindia iwayindia at gmail.com
Thu Aug 6 09:40:38 EDT 2009


Hi Guys,

I'm trying a proxy server where I could able to hit any remote server
running on any port.

I just did a few changes to the Hex*** proxy example published in NETTY.

for some reason, I'm not getting any response in the following code...
Please correct me...

//Removed imports
public class Proxy {

       public static void main(String[] args) throws Exception {
               System.err.println("Proxying *:8080 ...");

               ServerBootstrap sb = new ServerBootstrap(
                               new
NioServerSocketChannelFactory(Globals.getExecutor(),
                                               Globals.getExecutor()));

               ChannelPipeline pipeline = sb.getPipeline();

               pipeline.addLast("decoder", new HttpRequestDecoder());
               pipeline.addLast("encoder", new HttpResponseEncoder());
               pipeline.addLast("handler", new ProxyInboundHandler());

               sb.bind(new InetSocketAddress(8080));
       }
}

~~~~~~~~~~~~
//Removed Imports

@ChannelPipelineCoverage("one")
public class ProxyInboundHandler extends SimpleChannelUpstreamHandler {

       private volatile Channel outboundChannel;

       private volatile boolean readingChunks;

       private final StringBuilder responseContent = new StringBuilder();

       @Override
       public void messageReceived(ChannelHandlerContext ctx, MessageEvent
e)
                       throws Exception {
               HttpRequest request = null;

               if (!readingChunks) {
                       request = (HttpRequest) e.getMessage();

                       URI uri = new URI(request.getUri());

                       String remoteHost = uri.getHost();
                       int remotePort = uri.getPort() == -1 ? 80 :
uri.getPort();

                       // //////////////////////////////////////
                       //
///////////////////////////////////////////////////////////////////
                       // Suspend incoming traffic until connected to the
remote host.
                       final Channel inboundChannel = e.getChannel();
                       inboundChannel.setReadable(false);

                       // Start the connection attempt.
                       ClientBootstrap cb = new
ClientBootstrap(Globals.getChannelFactory());
                       cb.getPipeline().addLast("handler",
                                       new OutboundHandler(e.getChannel()));
                       ChannelFuture f = cb.connect(new
InetSocketAddress(remoteHost,
                                       remotePort));

                       outboundChannel = f.getChannel();
                       f.addListener(new ChannelFutureListener() {
                               public void operationComplete(ChannelFuture
future)
                                               throws Exception {
                                       if (future.isSuccess()) {
                                               // Connection attempt
succeeded:
                                               // Begin to accept incoming
traffic.
                                              
inboundChannel.setReadable(true);
                                       } else {
                                               // Close the connection if
the connection attempt has
                                               // failed.
                                               inboundChannel.close();
                                       }
                               }
                       });

                       if (request.isChunked()) {
                               readingChunks = true;
                       } else {
                               ChannelBuffer content = request.getContent();
                               if (content.readable()) {
                                       responseContent.append("CONTENT: "
                                                       +
content.toString("UTF-8") + "\r\n");
                               }
                               //writeResponse(request, e);
                       }
               }
       }

       @Override
       public void channelClosed(ChannelHandlerContext ctx,
ChannelStateEvent e)
                       throws Exception {
               if (outboundChannel != null) {
                       closeOnFlush(outboundChannel);
               }
       }

       @Override
       public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent
e)
                       throws Exception {
               e.getCause().printStackTrace();
               closeOnFlush(e.getChannel());
       }

       @ChannelPipelineCoverage("one")
       private class OutboundHandler extends SimpleChannelUpstreamHandler {

               private final Channel inboundChannel;

               OutboundHandler(Channel inboundChannel) {
                       this.inboundChannel = inboundChannel;
               }

               @Override
               public void messageReceived(ChannelHandlerContext ctx,
MessageEvent e)
                               throws Exception {
                       ChannelBuffer msg = (ChannelBuffer) e.getMessage();
                       System.out.println("<<< " +
ChannelBuffers.hexDump(msg));
                       inboundChannel.write(msg);
               }

               @Override
               public void channelClosed(ChannelHandlerContext ctx,
ChannelStateEvent e)
                               throws Exception {
                       closeOnFlush(inboundChannel);
               }

               @Override
               public void exceptionCaught(ChannelHandlerContext ctx,
ExceptionEvent e)
                               throws Exception {
                       e.getCause().printStackTrace();
                       closeOnFlush(e.getChannel());
               }
       }

       /**
        * Closes the specified channel after all queued write requests are
flushed.
        */
       static void closeOnFlush(Channel ch) {
               if (ch.isConnected()) {
                       ch.write(ChannelBuffers.EMPTY_BUFFER).addListener(
                                       ChannelFutureListener.CLOSE);
               }
       }
}

~~~~~~~~~~~~~~~~~~~~
public class Globals {
       // Configure the bootstrap.
       private static Executor executor = null;

       // Set up the event pipeline factory.
       private static ClientSocketChannelFactory channelFactory = null;

       private Globals() {
       }

       /**
        * @return the Channel Factory
        */
       public static synchronized ClientSocketChannelFactory
getChannelFactory() {
               if (channelFactory == null) {
                       channelFactory = new
NioClientSocketChannelFactory(getExecutor(),
                                       getExecutor());
               }

               return channelFactory;
       }

       /**
        * @return the executor
        */
       public static synchronized Executor getExecutor() {
               if (executor == null) {
                       executor = Executors.newCachedThreadPool();
                       ;
               }

               return executor;
       }
}

Please help me out.

Regards, Naveen


Rembert Magri wrote:
> 
> Hi Trustin,
> 
> I have been trying to use your Proxy Server Example but it seems I am
> getting the same error as Dave has already reported
> (http://markmail.org/message/kb7glbm573el2gg2). I gess it might be a
> concurrency issue, because when I turn the System.out.printn's off, it
> seems I get more ClosedChannelExceptions.
> Eventually I can load the entire redirected page without any problem, but
> in most cases the error keeps occurring and I aways have to try
> refreshing. I don't think it happens because of the load (I am redirecting
> a simple 3-frames html page).
> Do you think there is any way to solve this problem? I'm currently using
> Netty just to get this proxy working, and it would be great if I could
> show my dev team it has better performance AND reliability than Mina, for
> instance.
> 
> Thanks,
> Rembert
> 
> 
> Trustin Lee wrote:
>> 
>> Hi folks,
>> 
>> On popular demand, I added the proxy server example to the trunk:
>> 
>> http://viewvc.jboss.org/cgi-bin/viewvc.cgi/netty/trunk/src/main/java/org/jboss/netty/example/proxy/
>> 
>> It's a very simple proxy server that always connects to the same remote
>> address.  It prints out all inbound and outbound traffic in hexadecimal
>> form, hence named as 'HexDumpProxy'.
>> 
>> The code is pretty straightforward.  Please feel free to comment to make
>> it more comprehensive!
>> 
>> Cheers,
>> Trustin
>> 
>> PS: I will also write another example that demonstrates the transfer of
>> large file early next week. ;)
>> 
>> -- 
>> â?? Trustin Lee, http://gleamynode.net/
>> 
>> 
>>  
>> _______________________________________________
>> netty-users mailing list
>> netty-users at lists.jboss.org
>> https://lists.jboss.org/mailman/listinfo/netty-users
>> 
>> 
> 
> 

-- 
View this message in context: http://n2.nabble.com/Proxy-server-example-tp3066604p3398309.html
Sent from the Netty User Group mailing list archive at Nabble.com.



More information about the netty-users mailing list