Simple Proxy Server (Java)
虽然问题很多,而且处理简直就可以说是“没有处理”。但是,还是可以通过这个代理浏览网页,并且统计有多少流量流出和流入。代码如下。(这篇帖子就是同个这个proxy发的)。
1. 将serverSocket.close()改成if (serverSocket!=null) serverSocket.close();后,异常打印少了很多。没有null pointer exception了。
2. 将第一次从浏览器读取的request的count进行判断,如果<=0,就直接关掉socket;如果大于0,才进行其他处理。浏览网页速度变快了。不知道为什么。
view sourceprint?001 package network.proxy;
002
003 import java.io.*;
004 import java.net.*;
005 import java.util.*;
006
007 // internet server <--serverSocket--> proxy <--clientSocket--> client
008
009 public class MyProxy {
010 public static void main(String[] args) {
011 try {
012 new Thread(new SimpleProxyServer(8989)).start();
013 } catch (IOException e) {
014 e.printStackTrace();
015 }
016 }
017 }
018
019 class SimpleProxyServer implements Runnable {
020 private ServerSocket listenSocket;
021 public SimpleProxyServer(int port) throws IOException {
022 this.listenSocket = new ServerSocket(port);
023 }
024
025 public void run() {
026 for (;;) {
027 try {
028 Socket clientSocket = listenSocket.accept();
029 System.out.println("Create a new Thread to handle this connection");
030 new Thread(new ConnectionHandler(clientSocket)).start();
031 } catch (IOException e) {
032 e.printStackTrace();
033 }
034 }
035 }
036 }
037
038
039 class ProxyCounter {
040 static int sendLen = 0;
041 static int recvLen = 0;
042
043 public static void showStatistics() {
044 System.out.println("sendLen = " + sendLen);
045 System.out.println("recvLen = " + recvLen);
046 }
047 }
048
049 // must close sockets after a transaction
050 class ConnectionHandler extends ProxyCounter implements Runnable {
051 private Socket clientSocket;
052 private Socket serverSocket;
053
054 private static final int bufferlen = 8192;
055
056 public ConnectionHandler(Socket clientSocket) {
057 this.clientSocket = clientSocket;
058 }
059 public void run() {
060 // receive request from clientSocket,
061 //extract hostname,
062 //create a serverSocket to communicate with the host  
补充:软件开发 , Java ,