Visual C # implement the HTTP proxy service program

Source: Internet
Author: User

There are many types of network proxies. They are divided into HTTP proxy service programs and FTP Proxy service programs according to the protocol of proxy service program agents, the server that runs the proxy service program is also called the HTTP Proxy server and the FTP proxy server. The Web Proxy Service proxy described in this section is the HTTP protocol.

  I. Network Proxy types and implementation principles:

The network proxy service can be divided into Application Layer proxy, transport layer proxy, and SOCKS proxy according to the working level. The Application Layer proxy works on the application layer of the TCP/IP Reference Model. It supports proxy for the application layer protocol (such as HTTP and FTP. It provides the most control, but is not flexible, and must have corresponding protocol support. If the Protocol does not support proxies (such as SMTP and POP), you can only use the following proxies at the application layer, that is, transport layer proxies. The Transport Layer proxy interacts directly with the TCP layer, making it more flexible. The proxy server is required to have some real server functions: Listening to specific TCP or UDP ports, receiving client requests and sending corresponding responses to the client at the same time. Another proxy needs to change the client's IP stack, that is, the SOCKS proxy. It is the most powerful and flexible agent standard protocol available. SOCK V4 allows clients inside the proxy server to completely connect to external servers. SOCK V5 adds authorization and authentication to clients, so it is a highly secure proxy. The proxy described later in this section is a kind of proxy at the application layer. The proxy protocol is HTTP, that is, the Web proxy that is frequently seen.

A network proxy is a bridge between a client (a computer that requires proxy) and a server (a server that needs to access resources. To achieve this kind of bridge, the network proxy must meet the following conditions and is actually the process of running the proxy service:

(1). can receive and parse client requests.

(2) create a new connection to the server and forward the client's request information.

(3) receive the server feedback.

(4). the server response can be sent or interpreted and sent back to the client.

Figure 01 is a typical network proxy service model:


Figure 01: proxy service model

   Ii. Visual C # implement Web proxy service programs

Web Proxy service is the most common proxy service in proxy services. According to the proxy service level, it belongs to the application layer proxy and is the proxy for the HTTP protocol at the application layer in the TCP/IP Reference Model.

Web Proxy service is also a kind of proxy service, so it must also meet the basic conditions of proxy service. In the proxy service program described below, the functions are implemented in the following order.

(1). the proxy server listens to the port and receives Web request information sent by the client browser.

(2) After receiving Web request information from the client, the proxy server parses the address of the Web server, creates a Socket instance, and connects the instance to the Web server.

(3) Transmit the Web request data packet of the client to port 80 of the Web server through the created Socket.

(4) the proxy server program receives page data returned by the Web server.

(5) the proxy server program transfers the received data to the client to implement Web proxy.

Because the client browses an address, it needs to transmit a lot of Web request information. to process this information more quickly and accurately, the Web Proxy service uses multithreading to process each Web request. Careful readers may find that the proxy server software uses two sockets to process the Web request information of each client. One is used to receive/transmit the information of the client, one is to communicate with the Web server. To distinguish these two sockets, we name them all. The Socket used to talk to the server is called the service Socket. Scoket used to talk to the client machine is called the customer Socket.

The following describes how to compile the Web Proxy service program.

This example contains three parts:

· Create a Web proxy class.

· Instantiation of the Web Proxy service class.

· How to Implement the Web Proxy service through this Web proxy instance.

The following describes the implementation steps in the first part.

(1) create a Web proxy class

The procedure is as follows:

1. start Visual Studio. and select "file", "new", and "project". In the displayed "new project" dialog box, set "project type" to "Visual C # Project ", set "template" to "Windows application", enter "WebProxy" in the "name" text box, and enter "E:.. NET project, and then click OK. In this way, a new "WebProxy" folder named "WebProxy" is created in the "E: VS. NET project" Directory, which stores the "WebProxy" project file.

2. Select project> Add class. The add new item dialog box is displayed.

3. Set template to class]

4. Enter Proxy in the name text box and click open, as shown in 02.


Figure 02: Add new project dialog box in the Web Proxy Project

5. In the Solution Explorer window, double-click the Proxy. cs file to go to the editing interface of the Proxy. cs file.

6. Add the following code at the beginning of the Proxy. cs source file:

Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Using System. IO;

 

7. Use the following constructor to replace the default constructor. The following code creates a constructor in the Proxy class. The Proxy class has only one constructor, and this constructor has only one parameter. this parameter is a Socket object. It is mainly used to exchange data with the client and is a client Socket ..

Public Proxy (Socket socket)
{
//
// TODO: add the constructor logic here
//
This. clientSocket = socket;
}

8. Create the Run method in the Proxy class. The Run method is the only method in the Proxy class. The function is to receive HTTP requests from the client, send them to the Web server, then receive feedback data from the Web server, and send the data to the client. In order to implement data transmission in these two different aspects, the Run method is implemented through two Socket instances. When writing the Run method, pay attention to the following points:

(1). Because HTTP is an application layer protocol in the TCP/IP reference model, it is built on the TCP protocol, the protocol type used for the Socket instance created should be TCP. The following code creates a Socket instance that can send HTTP request commands to the Web server and receive feedback from the Web server:

Socket IPsocket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );

(2 ). another Socket is obtained when the Proxy service listens to the port number and receives a pending connection request. Using this Socket as the parameter, you can use the constructor in the Proxy class to create a Proxy instance. This Socket receives HTTP request information from the client and transmits data to the client.

Creating and using a Socket is the key to implementing the Web Proxy software. The specific implementation method is to enter the following code after the constructor code to create the Run method of the Proxy class:

Public void Run ()
{
String clientmessage = "";
// Store the HTTP request string from the client
String URL = "";
// Store the parsed address request information
Int bytes = ReadMessage (read, ref clientSocket, ref clientmessage );
If (bytes = 0)
{
Return;
}

Int index1 = clientmessage. IndexOf ();
Int index2 = clientmessage. IndexOf (, index1 + 1 );
If (index1 =-1) | (index2 =-1 ))
{
Throw new IOException ();
}
String part1 = clientmessage. Substring (index1 + 1, index2-index1 );
Int index3 = part1.IndexOf (/, index1 + 8 );
Int index4 = part1.IndexOf (, index1 + 8 );
Int index5 = index4-index3;
URL = part1.Substring (index1 + 4, (part1.Length-index5)-8 );

Try
{
IPHostEntry IPHost = Dns. Resolve (URL );
Console. WriteLine ("remote host name:" + IPHost. HostName );
String [] aliases = IPHost. Aliases;
IPAddress [] address = IPHost. AddressList;
Console. WriteLine ("Web Server IP address:" + address [0]);
// Parse the server address to be accessed
IPEndPoint ipEndpoint = new IPEndPoint (address [0], 80 );
Socket IPsocket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
// Create a Socket object connecting to the Web server
IPsocket. Connect (ipEndpoint );
// Socket connects to the Web server
If (IPsocket. Connected)
Console. WriteLine ("Socket is connected correctly! ");
String GET = clientmessage;
Byte [] ByteGet = ASCII. GetBytes (GET );
IPsocket. Send (ByteGet, ByteGet. Length, 0 );
// The proxy access software sends HTTP request commands to the server
Int32 rBytes = IPsocket. Receive (RecvBytes, RecvBytes. Length, 0 );
// The proxy access software receives feedback from the Web server.
Console. WriteLine ("number of received Bytes:" + rBytes. ToString ());
String strRetPage = null;
StrRetPage = strRetPage + ASCII. GetString (RecvBytes, 0, rBytes );
While (rBytes

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.