随笔-88  评论-77  文章-48  trackbacks-0

public class ProxyServer
{

    private static final int PORT = 9999;

    private ByteBuffer buffer = ByteBuffer.allocate(10240);

    private ProxyUtil proxyUtil = new ProxyUtil();

    private static String remoteHost = "";

    private static int remotePort = 80;

    private Logger log = ZXLogger.getLogger(ProxyServer.class.getName());

    //private Log log = LogFactory.getLog(ProxyServer.class);

    public ProxyServer()
    {
        //PropertyConfigurator.configure("src/log4j.properties");
    }

    /**
     * 方法名称:start <p>
     * 方法功能:运行代理服务器 <p>
     * 参数说明:<p>
     * 返回:void <p>
     * 作者:李明 <p>
     * 日期:2006年3月23日 <p>
     */
    public void runServer()
    {

        ServerSocket sSocket = null;
        ServerSocketChannel ssc = null;

        // 代理服务器监听开启

        Selector selector = null;
        try
        {
            ssc = ServerSocketChannel.open();
            sSocket = ssc.socket();
            sSocket.bind(new InetSocketAddress(PORT));

            selector = Selector.open();

            System.err.println("Listening Port is " + PORT);

            ssc.configureBlocking(false);
            ssc.register(selector, SelectionKey.OP_ACCEPT);
        }
        catch(ClosedChannelException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        catch(IOException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try
        {
            while(true)
            {

                int n = selector.select();

                if(n == 0)
                {
                    continue; // nothing to do
                }

                Set set = selector.selectedKeys();

                Iterator iter = set.iterator();

                while(iter.hasNext())
                {
                    SelectionKey key = (SelectionKey)iter.next();

                    if(key.isAcceptable())
                    {
                        ServerSocketChannel svrSocketChannel = (ServerSocketChannel)key.channel();
                        SocketChannel clientChannel = null;
                        try
                        {
                            clientChannel = svrSocketChannel.accept();
                        }
                        catch(IOException e)
                        {
                            // TODO Auto-generated catch block
                            if(clientChannel != null)
                            {

                                clientChannel.close();
                            }
                            if(key != null)
                            {
                                key.cancel();
                            }
                        }

                        send(clientChannel);

                    }
                    iter.remove();
                    log.info("************SEND  END*************");
                }
            }
        }
        catch(IOException e)
        {
            // TODO Auto-generated catch block
            log.info("ServerSocketChannel总体迭代发生核心异常\r\n" + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * 方法名称:send <p>
     * 方法功能:发送给客户信息 <p>
     * 参数说明:SocketChannel, String <p>
     * 返回:void <p>
     * 作者:李明 <p>
     * 日期:2006年3月23日 <p>
     *
     * @param channel
     * @param key
     * @throws IOException
     */
    public void send(SocketChannel clientChannel)
    {

        SocketChannel remoteSvrChannel = null;

        buffer.clear();
        int count;

        log.info("************SEND START*************");

        try
        {
            while((count = clientChannel.read(buffer)) > 0)
            {
                buffer.flip();

                byte[] bytebuffer = new byte[count];
                buffer.get(bytebuffer, 0, count);

                ByteBuffer bufferWrite = ByteBuffer.wrap(bytebuffer);

                byte[] b = new byte[bufferWrite.limit()];
                bufferWrite.get(b);
                String context = new String(b);

                // 打印客户请求代理服务器信息
                log.info(context);

                // 解析客户信息,得到远程主机和端口。
                proxyUtil.setUrl(context);
                setRemoteHost(proxyUtil.getHost());
                setRemotePort(proxyUtil.getPort());

                log.info("Remote Host " + getRemoteHost());
                log.info("Remote Port " + getRemotePort());

                if(remoteSvrChannel == null)
                {
                    InetSocketAddress inet = new InetSocketAddress(getRemoteHost(), getRemotePort());
                    try
                    {
                        remoteSvrChannel = SocketChannel.open(inet);
                        // remoteSvrChannel.configureBlocking(false);
                        // Socket remoteSvr = remoteSvrChannel.socket();
                        // remoteSvr.setSoTimeout(1000);
                        bufferWrite.flip();
                        remoteSvrChannel.write(bufferWrite);
                        buffer.clear();
                        int n;
                        while((n = remoteSvrChannel.read(buffer)) > 0)
                        {
                            log.info("n=" + n);
                            buffer.flip();
                            log.info("buffer.limit=" + buffer.limit());
                            clientChannel.write(buffer);
                        }
                    }
                    catch(java.nio.channels.UnresolvedAddressException ex)
                    {
                        log.info("主机地址访问无效\r\n" + ex.getMessage());
                    }
                    catch(IOException e)
                    {
                        // TODO Auto-generated catch block
                        try
                        {
                            if(remoteSvrChannel != null)
                            {
                                remoteSvrChannel.close();
                            }
                        }
                        catch(IOException e1)
                        {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                }
            }
        }
        catch(IOException e1)
        {
            // TODO Auto-generated catch block
            try
            {
                if(clientChannel != null)
                {
                    clientChannel.close();
                }
            }
            catch(IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        finally
        {
            try
            {
                if(remoteSvrChannel != null)
                {
                    remoteSvrChannel.close();
                }
                if(clientChannel != null)
                {
                    clientChannel.close();
                }
            }
            catch(IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // 打印远程服务器返回给客户端信息
//        buffer.flip();
//        byte[] b2 = new byte[buffer.limit()];
//        buffer.get(b2);
//        log.info(new String(b2));

        // 关闭远程和客户的连接

    }


    public static String getRemoteHost()
    {
        return remoteHost;
    }

    public static void setRemoteHost(String remoteHost)
    {
        ProxyServer.remoteHost = remoteHost;
    }

    public static int getRemotePort()
    {
        return remotePort;
    }

    public static void setRemotePort(int remotePort)
    {
        ProxyServer.remotePort = remotePort;
    }

    public ByteBuffer getBuffer()
    {
        return buffer;
    }

    public void setBuffer(ByteBuffer buffer)
    {
        this.buffer = buffer;
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        ProxyServer p = new ProxyServer();
        p.runServer();
    }
}

posted on 2006-04-28 11:26 崛起的程序员 阅读(595) 评论(0)  编辑  收藏 所属分类: java

只有注册用户登录后才能发表评论。


网站导航: