Simple Proxy Server (Java)

由於對java的network programmiing不太瞭解,因此就試着寫個simple proxy server練練手。java

雖然問題不少,並且處理簡直就能夠說是「沒有處理」。可是,仍是能夠經過這個代理瀏覽網頁,而且統計有多少流量流出和流入。代碼以下。(這篇帖子就是同個這個proxy發的)。瀏覽器

 

1. 將serverSocket.close()改爲if (serverSocket!=null) serverSocket.close();後,異常打印少了不少。沒有null pointer exception了。socket

 2. 將第一次從瀏覽器讀取的request的count進行判斷,若是<=0,就直接關掉socket;若是大於0,才進行其餘處理。瀏覽網頁速度變快了。不知道爲何。this

package network.proxy;

import java.io.*;
import java.net.*;
import java.util.*;

// internet server <--serverSocket--> proxy <--clientSocket--> client                                                                                                   

public class MyProxy {
    public static void main(String[] args) {
        try {
            new Thread(new SimpleProxyServer(8989)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class SimpleProxyServer implements Runnable {
    private ServerSocket listenSocket;
    public SimpleProxyServer(int port) throws IOException {
        this.listenSocket = new ServerSocket(port);
    }

    public void run() {
        for (;;) {
            try {
                Socket clientSocket = listenSocket.accept();
                System.out.println("Create a new Thread to handle this connection");
                new Thread(new ConnectionHandler(clientSocket)).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


class ProxyCounter {
    static int sendLen = 0;
    static int recvLen = 0;

    public static void showStatistics() {
        System.out.println("sendLen = " + sendLen);
        System.out.println("recvLen = " + recvLen);
    }
}

// must close sockets after a transaction                                                                                                                               
class ConnectionHandler extends ProxyCounter implements Runnable {
    private Socket clientSocket;
    private Socket serverSocket;

    private static final int bufferlen = 8192;

    public ConnectionHandler(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }
    public void run() {
        // receive request from clientSocket,                                                                                                                           
        //extract hostname,                                                                                                                                             
        //create a serverSocket to communicate with the host                                                                                                            
        // count the bytes sent and received                                                                                                                            
        try {
            byte[] buffer = new byte[bufferlen];
            int count = 0;

            InputStream inFromClient = clientSocket.getInputStream();
            count = inFromClient.read(buffer);
            String request = new String(buffer, 0, count);
            String host = extractHost(request);
            // create serverSocket                                                                                                                                      
            Socket serverSocket = new Socket(host, 80);
            // forward request to internet host                                                                                                                         
            OutputStream outToHost = serverSocket.getOutputStream();
            outToHost.write(buffer, 0, count);
            outToHost.flush();
            sendLen += count;
            showStatistics();
            // forward response from internet host to client                                                                                                            
            InputStream inFromHost = serverSocket.getInputStream();
            OutputStream outToClient = clientSocket.getOutputStream();
            while (true) {
                count = inFromHost.read(buffer);
                if (count < 0)
                    break;
                outToClient.write(buffer, 0, count);
                outToClient.flush();
                recvLen += count;
                showStatistics();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String extractHost(String request) {
        int start = request.indexOf("Host: ") + 6;
        int end = request.indexOf('\n', start);
        String host = request.substring(start, end - 1);
        return host;
    }
}
相關文章
相關標籤/搜索