Build your own Web server in C #

Source: Internet
Author: User
Tags socket socket error thread tostring
Web|web Service |web The personal collection of the server, only for archiving. Today, the disk is sorted, no place to put. Throw a blog.

Do not understand, don't ask me. Study for yourself.

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}", e);

}
}
public static void Main ()
{
MyWebServer MWS = new MyWebServer ();
}
public void Startlisten ()
{

int istartpos = 0;
String srequest;
String Sdirname;
String Srequestedfile;
String Serrormessage;
String Slocaldir;
Be aware of setting your own virtual directory/////////////////////////////////////
String smywebserverroot = "e:\\mywebserverroot\\"; Set up your virtual directory
//////////////////////////////////////////////////////////////////////////////////////////////////
String Sphysicalfilepath = "";
String sformattedmessage = "";
String sresponse = "";


while (true)
{
Accept New Connection
Socket mysocket = Mylistener.acceptsocket ();

Console.WriteLine ("Socket Type" +mysocket.sockettype);
if (mysocket.connected)
{
Console.WriteLine ("\nclient connected!! \n==================\nclient IP {0}\n ", mysocket.remoteendpoint);

byte[] breceive = new byte[1024];
int i = mysocket.receive (breceive,breceive.length,0);


Convert to String type
String sbuffer = Encoding.ASCII.GetString (breceive);


Process only "get" request type
if (sbuffer.substring (0,3)!= "get")
{
Console.WriteLine ("Process only GET request type ...");
Mysocket.close ();
Return
}

Find locations for "HTTP"
Istartpos = Sbuffer.indexof ("HTTP", 1);


String shttpversion = Sbuffer.substring (istartpos,8);


Get request type and file directory file name
Srequest = sbuffer.substring (0,istartpos-1);

Srequest.replace ("\", "/");


If the end is not a filename or ends with a "/"
if ((Srequest.indexof (".") <1) && (!srequest.endswith ("/"))
{
Srequest = srequest + "/";
}


Have to bring the request file name
Istartpos = Srequest.lastindexof ("/") + 1;
Srequestedfile = srequest.substring (Istartpos);


Get request File Directory
Sdirname = srequest.substring (Srequest.indexof ("/"), Srequest.lastindexof ("/")-3);


To get the virtual directory physical path
Slocaldir = Smywebserverroot;

Console.WriteLine ("Request file directory:" + Slocaldir);

if (slocaldir.length = 0)
{
Serrormessage = "Sendheader (Shttpversion, "", serrormessage.length, "404 Not Found", ref mysocket);
Sendtobrowser (Serrormessage, ref mysocket);
Mysocket.close ();
Continue
}


if (srequestedfile.length = 0)
{
Get request File name
Srequestedfile = "index.html";
}


/////////////////////////////////////////////////////////////////////
Get request file type (set to text/html)
/////////////////////////////////////////////////////////////////////

String Smimetype = "text/html";

Sphysicalfilepath = Slocaldir + srequestedfile;
Console.WriteLine ("Request file:" + Sphysicalfilepath);


if (file.exists (sphysicalfilepath) = = False)
{

Serrormessage = "Sendheader (Shttpversion, "", serrormessage.length, "404 Not Found", ref mysocket);
Sendtobrowser (Serrormessage, ref mysocket);

Console.WriteLine (Sformattedmessage);
}

Else
{
int itotbytes=0;

Sresponse = "";

FileStream fs = new FileStream (Sphysicalfilepath, FileMode.Open, FileAccess.Read, FileShare.Read);

BinaryReader reader = new BinaryReader (FS);
byte[] bytes = new Byte[fs. Length];
int read;
while (read = reader. Read (bytes, 0, bytes. Length))!= 0)
{
Sresponse = Sresponse + Encoding.ASCII.GetString (bytes,0,read);

Itotbytes = itotbytes + read;

}
Reader. Close ();
Fs. Close ();

Sendheader (Shttpversion, Smimetype, itotbytes, "OK", ref mysocket);
Sendtobrowser (bytes, ref mysocket);
Mysocket.send (bytes, bytes. length,0);

}
Mysocket.close ();
}
}
}


}

}



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.