Visual C # implements the HTTP Proxy service program

Source: Internet
Author: User
Tags aliases definition ftp connect socket thread tostring visual studio
Visual| Program Network Agent is very many types, according to the Agent Service Program Agent Protocol, divided into HTTP Proxy service program, FTP proxy service program, etc., the server running the Agent service program is called the HTTP proxy server and FTP proxy server. The Web Proxy service agent that is described in this section is the HTTP protocol.

   one. The type of network proxy and its realization principle:

The network Proxy service according to the work level, generally may divide into the application layer proxy, the Transport layer proxy and the SOCKS proxy. The application-tier proxy is the application layer that works on the TCP/IP reference model, and it supports proxies for application-layer protocols such as HTTP,FTP. It provides the most control, but not flexible, must have the appropriate protocol support. If the protocol does not support proxies (such as SMTP and POP), it can only be agents at the application level, or transport layer. The transport layer agent interacts directly with the TCP layer and is more flexible. Requires the proxy server to have a partial true server function: Listen for a specific TCP or UDP port, and the receiving client's request responds to the client at the same time. Another agent needs to change the IP stack of the client, that is, the socks agent. It is the most powerful and flexible agent standard protocol available. Sock V4 allows a client within the proxy server to fully connect to an external server, sock V5 increases the authorization and authentication of the client, so it is a more secure proxy. The agent that is described later in this section is a proxy on the application tier that is represented by HTTP, which is often seen as a Web proxy.

A network proxy is a bridge that connects the client (setting the computer that requires the proxy) and the server-side (the server that needs to access the resource). To implement this type of bridge, the network proxy must meet the following conditions, but it is also the process of running the Proxy service:

(1). Ability to receive and resolve requests from clients.

(2). Creates a new connection to the server, and according to the request information of the forwarding client.

(3). Receive information about the server's feedback.

(4). The ability to emit or interpret a response from the server and pass the response back to the client.

Figure 01 is a typical model diagram of a network proxy service:


Figure 01: Model of the Proxy service
   two. Visual C # implements the Web Proxy service program

Web Proxy service is the most common proxy service in proxy service, which belongs to Application layer agent in the level of proxy service, and is the proxy of HTTP protocol for application layer in TCP/IP reference model.

Web Proxy service is also a kind of proxy service, so it also satisfies the basic condition of agent service. In the Proxy service program described below, its functionality is implemented in the following order.

(1). A proxy server program listening port that receives Web request information sent by the client browser.

(2). After receiving the client Web request information, the Proxy server resolves the Web server's address and creates an instance of the socket that connects to the Web server with this instance.

(3). The client's Web request packet is routed to the Web server's 80 port via the created socket.

(4). The Proxy server program receives the Web server to return page data.

(5). The Proxy server program transmits the received data to the client and implements the Web Proxy.

The Web Proxy service uses multithreading to process each Web request because of the client's browsing of an address and the need to send a lot of Web request information for faster and more accurate processing of the information. Attentive readers may find that the proxy server software uses two sockets for each client's Web request, one for receiving/transmitting the client, and one for communicating with the Web server. In order to differentiate these two sockets, we put them all named, and the server conversations the socket, called the service socket, and the client machine dialog scoket, called the client socket.

The following is the beginning of the authoring of Web Proxy service programs.

This example consists of three parts:

• Create a Web proxy class.

· The instantiation of the class of the Web Proxy service.

• How to implement a Web proxy service through an instance of this Web proxy class.

Here is the first part of the specific implementation steps.

(i). Create a Web proxy class

The following steps are specific to the procedure below:

1. Start visual Studio. Net, select the file, new, Project menu, and then set the project type to Visual C # project in the New Project dialog box, set the template to Windows application, and in the name Enter "WebProxy" in the text box and enter "E:\VS" in the text box in the position. NET project, and then click the OK button. So in "E:\VS." NET project directory, you create a new "WebProxy" folder with a "WebProxy" project file.

2. Select Menu "Item" | "Add Class", pop-up "Add New Item" dialog box

3. Set the "template" to "class"

4. In the Name text box, type "Proxy" and click the "Open" button, as shown in Figure 02.


Figure 02:web The Add New Item dialog box in the Proxy project

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

6. At the beginning of the Proxy.cs source file, add the following code, which is the namespace to be used in the import Proxy.cs:

Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.IO; 7. Replace the default constructor with the following constructor. The following code creates a constructor in the proxy class. The proxy class has only one constructor, and the constructor has only one parameter, which is the socket object, which is used primarily for data exchange with the client and is a client socket.

Public Proxy (socket socket)
{
//
TODO: Add constructor logic here
//
This.clientsocket = socket;
}
8. To 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 and transfer them to the Web server, and then receive the feedback from the Web server and deliver the data to the client. In order to implement these two different aspects of data transfer, the Run method is implemented through two socket instances. When writing the Run method, be aware of the following points:

(1). Because HTTP is the application-layer protocol in the TCP/IP reference model, it is built on top of the TCP protocol, the protocol type used by the created socket instance should be the TCP protocol. The following code is to create a socket instance that can transfer 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). The other socket is when the agent service listens to the port number, receives the pending connection request, takes this socket as a parameter, and uses the constructor in the proxy class to create a proxy instance. This socket implementation receives HTTP request information from the client and transmits the data to the client.

Socket creation and use is the key to the implementation of Web proxy software, the implementation method is after the constructor code, enter the following code, create the proxy class Run method:

public void Run ()
{
String clientmessage = "";
Storing HTTP request strings from the client
String URL = "";
Store resolved 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]");
Resolves the address of the server to be accessed
IPEndPoint IPEndPoint = new IPEndPoint (address[0], 80);
Socket ipsocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
To create a socket object that connects to the Web server side
Ipsocket.connect (IPEndPoint);
Socket Connected Web server
if (ipsocket.connected)
Console.WriteLine (the Socket is connected properly!) " ) ;
string get = Clientmessage;
byte[] Byteget = ASCII. GetBytes (get);
Ipsocket.send (Byteget, byteget.length, 0);
Proxy access software for server-side transfer of HTTP request commands
Int32 rbytes = ipsocket.receive (recvbytes, recvbytes.length, 0);
Proxy access software receives feedback from the Web server side
Console.WriteLine ("Bytes Received:" + rbytes.tostring ());
String strretpage = null;
Strretpage = Strretpage + ASCII. GetString (recvbytes, 0, rbytes);
while (Rbytes > 0)
{
Rbytes = Ipsocket.receive (recvbytes, recvbytes.length, 0);
Strretpage = Strretpage + ASCII. GetString (recvbytes, 0, rbytes);
}
Ipsocket.shutdown (Socketshutdown.both);
Ipsocket.close ();
SendMessage (Clientsocket, strretpage);
The Agent service software transmits the received information to the client
}
catch (Exception Exc2)
{
Console.WriteLine (Exc2. ToString ());
}
}
Receive HTTP request data from the client
private int Readmessage (byte [] ByteArray, ref Socket S, ref String Clientmessage)
{
int bytes = S.receive (ByteArray, 1024, 0);
String messagefromclient = Encoding.ASCII.GetString (ByteArray);
Clientmessage = (String) messagefromclient;
return bytes;
}
Transfer data from the Web server to the client
private void SendMessage (Socket s, string message)
{
Buffer = new Byte[message. Length + 1];
int length = ASCII. GetBytes (message, 0, message. Length, Buffer, 0);
Console.WriteLine ("Bytes transmitted:" + length.) ToString ());
S.send (Buffer, length, 0);
}
9. Add the following code to the code area where the proxy class is defined, and the following code is a variable that defines the use of the proxy class, which is primarily used in the later definition of the Run method.

Socket Clientsocket;
byte[] Read = new byte[1024];
Defines a space for storing request packets from the client
Byte [] Buffer = null;
Encoding ASCII = encoding.ascii;
Set code
byte[] recvbytes = new byte[4096];
Defines a space for storing data returned by the Web server
10. The definition of the proxy class has thus been completed. It is very simple to instantiate a proxy class, exactly the same as before, with the following specific syntax:

Public Proxy (socket socket);
Parameter: Socket is a scoket instance

The following code creates a proxy instance:

Proxy proxy = new proxy (socket); (b). Use the proxy class to implement specific examples of Web proxies:

The following is the use of the proxy class created above to implement the Web proxy implementation steps, the proxy class is defined in the namespace WebProxy.

1. In Visual Studio. NET code Editor to open the Class1.cs file and enter the Class1.cs code editing interface.

2. Import the following namespaces at the beginning of the Class1.cs source file:

Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.IO;
Using System.Threading;
Using WebProxy;
Where the namespace WebProxy is where the proxy class is located, refer to the Proxy.cs source file
The definition of a namespace in.
3. To add the following code to the main function, the following code uses the proxy class to implement the Web Proxy.

const int port = 8000;
Define port number
TcpListener TcpListener = new TcpListener (port);
Console.WriteLine ("Listener Port Number:" + port.) ToString ());
TcpListener. Start ();
Listening port number
while (true)
{
Socket socket = TcpListener. AcceptSocket ();
And get the Scoket instance of transmitting and receiving data
Proxy proxy = new proxy (socket);
Proxy class instantiation
Thread thread = new Thread (new ThreadStart (proxy). Run));
Creating Threads
Thread. Start ();
Start thread
}
Save all the steps above, so a simple Web proxy is done. This web Agent listens on a 8000 port number.

(iii). Test your Web Code program:

Web agents can be implemented through two computers. One of these computers runs a Web proxy and acts as a Web proxy server. The other computer acts as a client, browsing through web pages through a web-based proxy server. After you have determined that the Web proxy software is running, the following are the necessary settings for the client.

1. Open IE Browser.

2. Select Tools | Internet Options to eject the Internet Options dialog box. In this dialog box, select the Connections page, and click the LAN Settings button. The local area network (LAN) Settings dialog box pops up. Select the Use a proxy server (X) for the LAN, which does not apply to dial-up and VPN connections, multiple-selection boxes. And in the Address text box, enter the proxy server's IP address, because the test proxy server IP address is "10.138.198.213", all also enter this IP address, in the "Port" text box, enter "8000". As shown in Figure 03:


Figure 03: The Client Settings Web Proxy Server dialog box
The client's settings are complete, and the computer that has the IP address "10.138.198.213" is already running the Web agent described above. Open the client's IE browser, and enter the URL you want to browse, you can browse through the Web proxy server, figure 04 is the Web Proxy service in the server-side runtime interface.


Figure 04:web Proxy Server Runtime interface
   Four. Summary

At this point a simple Web Proxy service software even if basically completed, through the introduction of the above content can be seen, although the principle of the implementation of proxy services relatively simple, but the actual implementation is still very cumbersome. Network proxy is a rich and complex topic, this section describes the agent service software, regardless of the implementation of the Protocol type, or implementation of the function, can only be a small part. I hope you can through the introduction of this article, combined with other relevant knowledge, to create a more powerful, more secure, using more stable network Agent service program.

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.