C # Implementation Web server

Source: Internet
Author: User
Tags header socket socket error thread tostring
Web|web Service |web Server This is just a simple use of C # to write a Web server, only to achieve the get way of the request for HTML files, interested friends can continue to develop more functions on this basis, little Brother Learning C # soon, if there are errors and omissions, hope to see cool!!

Summary:

The work of WWW is based on the client/server computing model, consisting of a Web browser (client) and a Web server (server), which uses Hypertext Transfer Protocol (HTTP) to communicate, and the principle of HTTP protocol includes four steps: connection, request, reply. According to the principle of the HTTP protocol mentioned above, this paper realizes the method of Web server program of Get request by creating TcpListener class object, listening port 8080, waiting, accepting client connecting to port 8080, creating input stream and output stream associated with socket word; Reads the client's request information, if the request type is get, obtains the access HTML file name from the request information, if the HTML file exists, opens the HTML file, returns the HTTP header information and the HTML file contents to the Web browser via the socket, and then closes the file. Otherwise, send an error message to the Web browser. Finally, close the socket word that is connected to the appropriate Web browser.

The function principle of HTTP protocol

WWW is an application system with Internet as transmission medium, the most basic transmission unit of WWW is Web page. The work of WWW is based on the client/server computing model, consisting of a Web browser (client) and a Web server (server), which communicates with a Hypertext Transfer Protocol (HTTP). The HTTP protocol, which is based on TCP/IP protocol, is an application layer protocol between Web browsers and Web servers, and is a universal, stateless, object-oriented protocol. The principle of the HTTP protocol includes four steps:

Connection: The Web browser establishes a connection to the Web server, opens a virtual file called a socket (socket), which marks the successful connection establishment.

Request: The Web browser submits the request to the Web server via the socket. HTTP requests are typically a GET or post command (the post is used for the pass of form parameters). The format of the Get command is:

Get path/filename http/1.0

The filename indicates the file being accessed, and http/1.0 indicates the HTTP version used by the Web browser.

Answer: When a Web browser submits a request, it is routed to the Web server via the HTTP protocol. When the Web server receives the transaction, the processing results are returned to the Web browser via HTTP, which displays the requested page in the Web browser.

For example: Assuming the client has established a connection with www.mycomputer.com:8080/mydir/index.html, the Get command is sent: Get/mydir/index.html http/1.0. A Web server with host name www.mycomputer.com searches its document space for Mydir file index.html of subdirectories. If the file is found, the Web server transmits the contents of the file to the appropriate Web browser.

To tell the Web browser what type of content to transfer, the Web server first transmits some HTTP header information and then transmits the specific content (that is, the HTTP body information), separating the HTTP header information from the HTTP body information with a blank line.

The common HTTP header information is:

①http 1.0 OK

This is the first line answered by the Web server, listing the HTTP version number and the answer code that the server is running. The code "OK" indicates that the request is complete.

②mime_version:1.0

That indicates the version of the MIME type.

③content_type: Type

This header information is very important and it indicates the MIME type of the HTTP body information. Such as: Content_type:text/html indicates that the transmitted data is an HTML document.

④content_length: Length Value

It indicates the length (in bytes) of the HTTP body information.

Close connection: When the answer is complete, the Web browser and Web server must be disconnected to ensure that other Web browsers can establish a connection with the Web server.

Second, C # Implementation of Web server function program design

According to the principle of the HTTP protocol mentioned above, the method of implementing the Web server program of Get request is as follows:

Create a TcpListener class object that listens on a port (arbitrary input idle port such as: 8080).

Wait, accept the client to connect to the port, get the socket connected to the client;

Reads the request information submitted by a row of clients from the input stream associated with the socket, in the format of the request information: Get path/filename http/1.0

Gets the request type from the request information. If the request type is get, the access HTML file name is obtained from the request information. When there is no HTML file name, the index.html is used as the filename;

If the HTML file exists, open the HTML file, pass the HTTP header information and the HTML file contents back to the Web browser via the socket, and then close the file. Otherwise send the error message to the Web browser;

Closes the socket word that is connected to the appropriate Web browser.


The implementation code is as follows:
webserver.cs//////////////////


Namespace Cnnbsun.webserver
{
Using System;
Using System.IO;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading;


Class MyWebServer
{

Private TcpListener MyListener;
private int port = 8080; Select any idle port

Start and listen to the port
Start a concurrent listening process at the same time
Public MyWebServer ()
{
Try
{
Start and listen to the port
MyListener = new TcpListener (port);
Mylistener.start ();
Console.WriteLine ("Web Server Running ... Press ^c to Stop ... ");
Start a simultaneous listening process ' startlisten '
Thread th = new Thread (new ThreadStart (Startlisten));
Th. Start ();

}
catch (Exception e)
{
Console.WriteLine ("Error while listening to port:" +e.tostring ());
}
}
public void Sendheader (string shttpversion, string smimeheader, int itotbytes, string sstatuscode, ref Socket Mysocket)
{

String sbuffer = "";

if (smimeheader.length = 0)
{
Smimeheader = "text/html"; Default text/html
}

Sbuffer = sbuffer + shttpversion + sstatuscode + "\ r \ n";
Sbuffer = Sbuffer + "server:cx1193719-b\r\n";
Sbuffer = Sbuffer + "Content-type:" + Smimeheader + "\ r \ n";
Sbuffer = Sbuffer + "accept-ranges:bytes\r\n";
Sbuffer = Sbuffer + "Content-length:" + itotbytes + "\r\n\r\n";

byte[] Bsenddata = Encoding.ASCII.GetBytes (sbuffer);

Sendtobrowser (Bsenddata, ref mysocket);

Console.WriteLine ("Total Bytes:" + itotbytes.tostring ());

}

public void Sendtobrowser (String sData, ref Socket Mysocket)
{
Sendtobrowser (Encoding.ASCII.GetBytes (sData), ref mysocket);
}

public void Sendtobrowser (byte[] bsenddata, ref Socket Mysocket)
{
int numbytes = 0;

Try
{
if (mysocket.connected)
{
if ((numbytes = Mysocket.send (Bsenddata, bsenddata.length,0)) = = 1)
Console.WriteLine ("Socket Error cannot Send Packet");
Else
{
Console.WriteLine ("No.") of bytes Send {0} ", numbytes);
}
}
Else
Console.WriteLine ("Connection Failed ...");
}
catch (Exception e)
{
Console.WriteLine ("Error occurred: {0} &qu



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.