首页 > 开发 > 综合 > 正文

用C#建立自己的Web服务器

2024-07-21 02:19:13
字体:
来源:转载
供稿:网友
,欢迎访问网页设计爱好者web开发。个人珍藏,仅为存档.今天整理磁盘,没处放.扔blog.

看不懂,别问我.自己研究.

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 ; // 选者任何闲置端口

//开始兼听端口
//同时启动一个兼听进程
public mywebserver()
{
try
{
//开始兼听端口
mylistener = new tcplistener(port) ;
mylistener.start();
console.writeline("web server running... press ^c to stop...");
//同时启动一个兼听进程 'startlisten'
thread th = new thread(new threadstart(startlisten));
th.start() ;

}
catch(exception e)
{
console.writeline("兼听端口时发生错误 :" +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"; // 默认 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("连接失败....");
}
catch (exception e)
{
console.writeline("发生错误 : {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;
/////////////////////////////////////注意设定你自己的虚拟目录/////////////////////////////////////
string smywebserverroot = "e://mywebserverroot//"; //设置你的虚拟目录
//////////////////////////////////////////////////////////////////////////////////////////////////
string sphysicalfilepath = "";
string sformattedmessage = "";
string sresponse = "";


while(true)
{
//接受新连接
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) ;


//转换成字符串类型
string sbuffer = encoding.ascii.getstring(breceive);


//只处理"get"请求类型
if (sbuffer.substring(0,3) != "get" )
{
console.writeline("只处理get请求类型..");
mysocket.close();
return;
}

// 查找 "http" 的位置
istartpos = sbuffer.indexof("http",1);


string shttpversion = sbuffer.substring(istartpos,8);


// 得到请求类型和文件目录文件名
srequest = sbuffer.substring(0,istartpos - 1);

srequest.replace("//","/");


//如果结尾不是文件名也不是以"/"结尾则加"/"
if ((srequest.indexof(".") <1) && (!srequest.endswith("/")))
{
srequest = srequest + "/";
}


//得带请求文件名
istartpos = srequest.lastindexof("/") + 1;
srequestedfile = srequest.substring(istartpos);


//得到请求文件目录
sdirname = srequest.substring(srequest.indexof("/"), srequest.lastindexof("/")-3);


//获取虚拟目录物理路径
slocaldir = smywebserverroot;

console.writeline("请求文件目录 : " + slocaldir);

if (slocaldir.length == 0 )
{
serrormessage = "<h2>error!! requested directory does not exists</h2><br>";
sendheader(shttpversion, "", serrormessage.length, " 404 not found", ref mysocket);
sendtobrowser(serrormessage, ref mysocket);
mysocket.close();
continue;
}


if (srequestedfile.length == 0 )
{
// 取得请求文件名
srequestedfile = "index.html";
}


/////////////////////////////////////////////////////////////////////
// 取得请求文件类型(设定为text/html)
/////////////////////////////////////////////////////////////////////

string smimetype = "text/html";

sphysicalfilepath = slocaldir + srequestedfile;
console.writeline("请求文件: " + sphysicalfilepath);


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

serrormessage = "<h2>404 error! file does not exists...</h2>";
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, " 200 ok", ref mysocket);
sendtobrowser(bytes, ref mysocket);
//mysocket.send(bytes, bytes.length,0);

}
mysocket.close();
}
}
}


}

}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表