Simple Proxy Server (Java)(二)

2014-11-24 08:36:40 · 作者: · 浏览: 4
inFromClient.read(buffer);

070 String request = new String(buffer, 0, count);

071 String host = extractHost(request);

072 // create serverSocket

073 Socket serverSocket = new Socket(host, 80);

074 // forward request to internet host

075 OutputStream outToHost = serverSocket.getOutputStream();

076 outToHost.write(buffer, 0, count);

077 outToHost.flush();

078 sendLen += count;

079 showStatistics();

080 // forward response from internet host to client

081 InputStream inFromHost = serverSocket.getInputStream();

082 OutputStream outToClient = clientSocket.getOutputStream();

083 while (true) {

084 count = inFromHost.read(buffer);

085 if (count < 0)

086 break;

087 outToClient.write(buffer, 0, count);

088 outToClient.flush();

089 recvLen += count;

090 showStatistics();

091 }

092 } catch (IOException e) {

093 e.printStackTrace();

094 } finally {

095 try {

096 clientSocket.close();

097 serverSocket.close();

098 } catch (IOException e) {

099 e.printStackTrace();

100 }

101 }

102 }

103

104 private String extractHost(String request) {

105 int start = request.indexOf("Host: ") + 6;

106 int end = request.indexOf('\n', start);

107 String host = request.substring(start, end - 1);

108 return host;

109 }

110 }