Write your own web server (I) to gain a deep understanding of the Communication Principles between ASP. NET browsers and servers.

Source: Internet
Author: User

A few days ago, we saw a Socket-based chat tool by 51cto.
Suddenly, I wrote a simple web server.
It took me half a day to write down a document and share it specially (if you have any typo, please forgive me)

Someone said that I admire writing code with notepad last time. In fact, there is nothing. I can write code wherever I am skilled.
First, this server technology requires Commission, multithreading, and socket communication.
Delegate, here we will mention it at will. If you don't understand it, go to another place to find some materials for study.
I. Delegation
Delegation is a safe function pointer. That is to say, we can pass the delegate as a parameter.
A delegate is a type of reference method. Once a method is assigned to the Delegate, the delegate has the same behavior as the delegate. Commission

The use of the delegate method can have parameters and return values like any other method.
I will not explain it more here, which is not the focus of my speech. You can learn about the specific usage of the server later.

Ii. Multithreading
We generally say that every application is a process, and a process can have multiple threads. However, we create an application

By default, a program has only one thread (single thread), that is, the main thread. It is also called a UI thread.
Let's take a simple example to illustrate the problems caused by a single thread.
Put a button on the form, click the button to trigger an event, and create a loop in this event
For (int I = 0; I <9999999999; I ++)
{

}
MessageBox. Show ("cyclic completion ");
We do not do anything in the loop. Run. We can see that our form can be moved before clicking the button. When I

After clicking the button, the form cannot be moved again.
That is to say, when we loop, our UI thread goes through the loop, and there is no idle time to process an operation of the form.
Advantages of multithreading: allows a program to process multiple tasks at the same time.
For example, when there are too many things in a company, the boss will consider asking some people to help him do things. Then everyone is

One thread.

Multi-threaded operations are simple. They are a class, Thread.
Now that we know this class, we are creating a thread.

Thread thread = new Thread (
Okay. At this time, we found that some data types we don't know need to be passed in. We can go to the definition and see in the constructor.

There are two data types of parameters
One is ParameterizedThreadStart.
The other is ThreadStart.
Let's look at the definitions separately. Well, both are delegates. The former must contain parameters of the object type, while the latter does not. None

Return type.

That is to say, we need to pass a method in the new thread (every person in the company must give you some tasks, let

What do you do, you cannot spend money to invite you to play ).
The problem caused by the preceding single thread is solved. The code we want to execute is put into a method, which follows

The signature of the preceding two types of delegation is defined.

Because we do not need parameters, we use the second delegate.
Thread thread = new Thread (Count );
Thread. start ();
Public void Count ()
{......}

In this case, OK. However, we will find another problem. When the cycle is not over, We click X to close the window, but the main process

And exit, that is, we have a lock on. When the loop is complete, the dialog box is displayed. Click OK.

Backend master
The program will exit.

The foreground thread and background thread are involved here.
Foreground thread: the program can be closed only when all foreground threads are closed.
Background thread: As long as all foreground threads end, background threads automatically end.
So we need to set this thread as a background thread.
Thread thread = new Thread (Count );
Thread. isbackground = true;
Thread. start ();

After we use a delegate without parameters, how can we use a delegate with parameters.
Public void Count (object name)
{......}
Thread thread = new Thread (Count );
Thread. isbackground = true;
Thread. start ();
This is not feasible because our method requires parameters, but we have not passed the parameters.
You can see that the start method has another overload, and you can pass an object-type parameter. What do you think?

. Because the delegate parameters with parameters are of the object type.
In fact, this is the case. I don't need to go on with it.

Iii. Socket
Socket is usually called "Socket". It is used to describe the IP address and port and is a communication chain handle. To put it bluntly,

Is a tool for communication between two applications.
Just as you call you, why can you talk? The mobile phone is Socket.
We imagine that your father is a server, and you are a client.
1. First, your father must have a mobile phone and a mobile phone model. It must not be a toy mobile phone. This process is to create a socket object

We generally use the constructor of the three parameters.
Socket sokServer = new Socket (AddressFamily. InterNetwork, SocketType. Stream,

ProtocolType. Tcp); specifies the socket addressing scheme, socket type (Stream connection), Protocol Type TCP protocol.

2. How can we find your dad's phone number through the phone waves? If there are so many mobile phones in the world, your father must have a mobile phone card.

You can communicate with your father based on the phone card number. In this case, we need to specify the IP address and port for the network application.

The IP address is used to find the computer where your current application is located, and the port is used to find the location of your application on the computer.
IPAddress address = IPAddress. Parse (txtIP. Text );
IPEndPoint port = new IPEndPoint (address, int. Parse (txtPort. Text ));
On the form of my server, there are two text boxes and one button, txtIp (127.0.0.1), txtPort (8088), btnListen

3. With a cell phone and a cell phone card, the cell phone card must be inserted into the cell phone. That is to say, our socket needs to be bound

The IP address and port of the server.
SokServer. Bind (port );

4. The card is inserted into the mobile phone. How to answer the phone without starting the instance. So we need to start the instance.
That is, listening to client requests
SokServer. Listen (10); what is 10 here? For example, many mobile phones can receive multiple calls at the same time. 10 here means

My mobile phone can receive 10 calls at the same time.

5. Well, your dad's cell phone is all ready and you will be waiting for a call. First, you have a client, and your mobile phone is also a socket.

Word.
Create a socket first.
Socket sokClient = new Socket (AddressFamily. InterNetwork, SocketType. Stream,

ProtocolType. Tcp );

6. When you call your dad, you have to specify your dad's number, so you need to specify the IP address and port of the server you want to connect.
IPAddress address = IPAddress. Parse (txtIP. Text );
IPEndPoint port = new IPEndPoint (address, int. Parse (txtPort. Text ));
TxtIp (127.0.0.1), txtPort (8088), the IP address and port are the IP address and port on the server side.

7. Now you are calling, that is, connecting to the server.
SokClient. Connect (port );

8. Now your phone number has passed, that is, the connection request has been sent. You have to accept your dad's cell phone.

You speak.
Your dad heard the phone ring now and took the phone out to answer the phone. He pressed the answer key.
That is to say, the server receives the request from the client.
SokServer. Accept ();
TxtShow. appendText ("connection accepted successfully... \ r \ n ");

9. You said to your dad, "Dad, I have no money. Pay me some money ".

SokClient. send (), we find that a binary array is passed, so we first define an array and specify it as 1 M
Byte [] arrMsg = new byte [1024*1024]
Save the data we want to send to the array. We wanted to send a string. Now we define a byte array.

The length is specified, but the conversion of string to byte is not exactly equal to 1024*1024.

Convert the string into a byte array,
Byte [] arrMsg = System. Text. Encoding. UTF8.GetBytes (txtInput. Text. Trim ());
SokClient. Send (arrMsg );
10. Your dad needs to receive the message and then talk to you.
That is to say, the server must receive client requests.
SokServer. Accept ();
TxtShow. appendText ("receive server requests ").
Byte [] msgArr = new byte [1024*1024]; // The buffer of the received message
Int length = 0;
// Receives the message data sent by the server.
Length = sokServer. Receive (msgArr); // Receive will block the thread
String strMsg = System. Text. Encoding. UTF8.GetString (msgArr, 1, length-1 );
TxtShow. AppendText (strMsg + "\ r \ n ");

11. When your dad hears your news, he will talk to you. The client communicates with the browser, and the client uses a socket to communicate.

The server also uses Sockets for receiving. However, if the server needs to communicate with the client, you must create another socket.

Specifically responsible for communicating with this client. Because a server has multiple clients to access. Just like your dad's phone may have

When multiple people call, you must communicate with everyone who calls you. We know that

You need to specify the IP address and port, that is, to specify who to communicate. You cannot ask your dad for a cell phone to communicate with you alone.

Right. Then your father cannot buy several hundred mobile phones.
The server certainly won't know which client you want to communicate. This does not need to be considered. We can see that

The Accept method returns a socket. That is to say, when your client communicates with the server

A socket is automatically created, which is responsible for communicating with you.
Socket sokWatch = sokServer. Accept (); then we use a Socket to Accept it. This Socket is specially responsible

This client sends the message for communication.
12, but the Accept method will block the running of the current thread, which will give the user a bad feeling. So we need to create

Threads to specifically accept client requests. Let's create a method for listening. However, you can only execute this method.

Once, but our server can send messages from clients at any time. So we need to listen all the time. Therefore

Create a loop. Defines whether a global bool variable identifies a listener. The value is true.
Bool isWatch = true;
Public void Watch ()
{
While (isWatch)
{
Socket sokWatch = sokServer. Accept ();
TxtShow. AppendText (sokWatch. RemoteEndPoint. ToString ());
}
}
SokWatch. RemoteEndPoint. ToString () to obtain the IP address and port of the client.

It is not allowed when we create a thread to operate the interface elements. Just like the company's sales department wants to come to C # code

It must pass a test. Check whether you have the strength.
We need to cancel the cross-thread interface control check on this form.
Put in the constructor.
TextBox. checkforillegalcrossthreadcils = false; // disable the cross-thread control modification check.

In this way, the client requests are monitored cyclically.

The following is all the code.

Server code:
Public FormServer ()
{
InitializeComponent ();
TextBox. checkforillegalcrossthreadcils = false;
}

Thread thread = null;
Socket sokServer;
Private void btnListen_Click (object sender, EventArgs e)
{
// Create a socket for the server
SokServer = new Socket (AddressFamily. InterNetwork, SocketType. Stream,

ProtocolType. Tcp );
IPAddress address = IPAddress. Parse (txtIP. Text );
IPEndPoint port = new IPEndPoint (address, int. Parse (txtPort. Text ));
// Bind the port and Ip address to sokcet
SokServer. Bind (port );
// Start listening for client requests
SokServer. Listen (10 );
// Because the Accept method that accepts the request will block the current thread, create a new thread
Thread = new Thread (Watch );
// Set it to a background thread
Thread. IsBackground = true;
// Enable the thread
Thread. Start ();
TxtShow. AppendText ("server enabled successfully ");

}
Bool isWatch = true;
Public void Watch ()
{
// Can communicate with multiple clients multiple times
While (isWatch)
{
// When receiving a request sent from the client, immediately create a socket to communicate with it

Letter.
Socket sokWatch = sokServer. Accept ();
// Obtain the Client IP address and port
TxtShow. AppendText (sokWatch. RemoteEndPoint. ToString ());
Byte [] msgArr = new byte [1024*1024];
// Save the data sent from the client to the byte array because the sent data is in bytes.

Group
// The length of the received data, because the byte array created above is 1024*1024, but the number of sent data

Generally, it is not so big, so we only need to convert the data from 0 to length when converting the byte array into a string.
Int length = sokWatch. Receive (msgArr );
String strMsg = System. Text. Encoding. UTF8.GetString (msgArr, 0,

Length );
TxtShow. AppendText (strMsg + "\ r \ n ");
}
}

Client code:
Public FormClient ()
{
InitializeComponent ();
TextBox. checkforillegalcrossthreadcils = false;
}
Socket sokClient = null;
Private void btnConn_Click (object sender, EventArgs e)
{
SokClient = new Socket (AddressFamily. InterNetwork, SocketType. Stream,

ProtocolType. Tcp );
IPAddress address = IPAddress. Parse (txtIp. Text );
IPEndPoint port = new IPEndPoint (address, int. Parse (txtPort. Text ));
SokClient. Connect (port );
}

Private void btnSend_Click (object sender, EventArgs e)
{
Byte [] arrMsg = System. Text. Encoding. UTF8.GetBytes (txtMsg. Text );
SokClient. Send (arrMsg );
}

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.