//获取虚拟目录物理路径 sLocalDir = sMyWebServerRoot;
Console.WriteLine("请求文件目录 : " + sLocalDir);
if (sLocalDir.Length == 0 ) { sErrorMessage = "Error!! Requested Directory does not exists "; 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 = "404 Error! File Does Not Exists..."; 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(); } } }
}
}
///////////结束////////////////
将文件编译成EXE文件,就实现了简单的WEB服务器功能! 可以设定一个虚拟目录,进行测试! |