How http Proxy works (1)

Source: Internet
Author: User

First, let's give a simple example. This example shows how the HTTP protocol works: Suppose there is a person (this person is a browser) who needs to contact the outside to get what he needs, the contact between this person and everyone outside the company must be sent via a letter. First, he writes the address of the other party and the name of the other party on the envelope, you also have your own address and name. Your own address represents the domain name in the URL, and the name represents the port number. what you need is a specific URL. Then he delivers the letter to the recipient's mailbox. when receiving a letter, the recipient will deliver the desired item to the person's mailbox Based on the address and name on the envelope. the envelope corresponds to the HTTP protocol. let's take a look at the content of an HTTP protocol: GET http://www.mytest.com: 6666/index.html HTTP/1.1 Accept: */* Accept-Language: zh-cnUser-Agent: mytestAccept-Encoding: gzip, deflateConnection: keep-AliveHost: www.mytest.com: 6666 is equivalent to the content written by the sender on the envelope. The first line is the address of the sender and what you need, in addition, this person wrote such content on the envelope: HTTP/1.1, which means: Kiss, the content on this envelope was written in version 1.1 as discussed at the beginning. Accept: */* // you can recognize anything you send. Accept-Language: zh-cn // you can use Chinese for your reply. User-Agent: mytest // my current environment condition Accept-Encoding: gzip, deflate // you can use zhongtong, Shentong, and puyou, I cannot accept others. Connection: Keep-Alive // come first. I may have something to send to you. Host: www.mytest.com: 6666 // dear user, This is my address. The above is the request process in the HTTP protocol. The response process is similar to this. Next, let's talk about the proxy process. Now we hope that when this person sends emails to external users, they don't need to run the mail by themselves, but we have agents to send the emails. Let's assume we are post offices. When a person sends a mail to another person, he directly sends the mail to the post office. Then, he does not need to worry about it. When the Post Office receives the mail, he sends it to the recipient Based on the address on the envelope, then, the recipient's response is taken back and sent to the sender. the HTTP Proxy acts as the post office function. Next, we first use the simplest code to implement an http proxy. To run this code correctly, we need a software Fiddler. Why do we need Fiddler, because we have only one staff member in this small post office, who is illiterate and does not understand what is written on the envelope, he can only forward this letter to a more professional post office Fiddler. here we only talk about the forwarding process, so you can ignore Fiddler. the most important thing is not to be affected by Fiddler. Code first: Step 1: open a SocketServer and listen to the specified port. When a request arrives, a new thread response starts to explain the key logic as much as possible, I removed the exception capture and resource release code [java] socketServer = new ServerSocket (PORT); while (true) {// Our employee is waiting for the user to arrive. // he never even has a rest. The only way to stop him is to kill his final Socket socket = socketServer. accept (); Runnable job = new Runnable () {public void run () {// a user has finally sent a message and started working on the service (socket );}}; threadPoolExecutor.exe cute (job);} Then let's look at the service method: [java] socke T. setSoTimeout (10000); socket. setKeepAlive (false); InputStream inputStream = socket. getInputStream (); OutputStream outputStream = socket. getOutputStream (); Socket remote = new Socket ("127.0.0.1", 8888); InputStream remoteInputStream = remote. getInputStream (); OutputStream remoteOutputStream = remote. getOutputStream (); // send the message to copy (inputStream, remoteOutputStream, 4096); remote. setSoTimeout (10000); // Send the response of the other party to the sender copy (remoteInputStream, outputStream, 4096); the service method is very simple, and there are only 10 lines of core code. On the whole, there are less than 20 lines of core code, however, it can run normally. of course, the performance is poor. It takes several minutes to open a complex page. however, it is easy to understand how the http Proxy works. in the next article, we will further expand and increase the capabilities of this employee. Now he is very stupid. The following is the complete code: [java]/** $ RCSfile: SimpleHttpProxy1.java, v $ * $ Revision: 1.1 $ * $ Date: $ ** Copyright (C) 2008 Skin, Inc. all rights reserved. ** This software is the proprietary information of Skin, Inc. * Use is subject to license terms. */package test.com. skin. http. proxy; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java.net. serverSock Et; import java.net. socket; import java.net. socketTimeoutException; import java. util. concurrent. arrayBlockingQueue; import java. util. concurrent. blockingQueue; import java. util. concurrent. threadPoolExecutor; import java. util. concurrent. timeUnit;/*** <p> Title: SimpleHttpProxy1 </p> * <p> Description: </p> * <p> Copyright: Copyright (c) 2006 </p> * @ author xuesong.net * @ version 1.0 */public class Sim PleHttpProxy1 {public static final int PORT = 6666; public static final byte [] CRLF = new byte [] {0x0D, 0x0A }; /*** @ param args */public static void main (String [] args) {ServerSocket socketServer = null; BlockingQueue <Runnable> blockingQueue = new ArrayBlockingQueue <Runnable> (1024 ); threadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor (512,102 4, 30000, TimeUnit. SECONDS, blockingQueue); Try {socketServer = new ServerSocket (PORT); while (true) {try {final Socket socket = socketServer. accept (); Runnable job = new Runnable () {public void run () {service (socket) ;}}; threadPoolExecutor.exe cute (job);} catch (SocketTimeoutException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}} catch (Exception e) {e. printStackTrace ();} finally {if (socketServer! = Null) {try {socketServer. close () ;}catch (IOException e) {}}} private static void service (Socket socket) {Socket remote = null; try {socket. setSoTimeout (2000); socket. setKeepAlive (false); InputStream inputStream = socket. getInputStream (); OutputStream outputStream = socket. getOutputStream (); remote = new Socket ("127.0.0.1", 8888); InputStream remoteInputStream = remote. getInputStream (); OutputStream remoteOutputStream = remote. getOutputStream (); try {copy (inputStream, remoteOutputStream, 4096);} catch (SocketTimeoutException e) {} catch (Exception e) {e. printStackTrace ();} try {remote. setSoTimeout (10000); copy (remoteInputStream, outputStream, 4096);} catch (SocketTimeoutException e) {} catch (Exception e) {e. printStackTrace () ;}} catch (Exception e) {e. printStackTrace ();} Finally {try {if (socket! = Null) {socket. close () ;}} catch (IOException e) {}try {if (remote! = Null) {remote. close () ;}} catch (IOException e) {e. printStackTrace () ;}} private static void copy (InputStream inputStream, OutputStream outputStream, int bufferSize) throws IOException {int length = 0; byte [] buffer = new byte [bufferSize]; while (length = inputStream. read (buffer, 0, bufferSize)>-1) {outputStream. write (buffer, 0, length);} outputStream. flush ();}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.