创建Console应用程序,粘贴一下代码,创建E://MyWebServerRoot//目录,作为虚拟目录,亲自测试通过,

创建Console应用程序,粘贴一下代码,创建E://MyWebServerRoot//目录,作为虚拟目录,亲自测试通过,

有一个想法,调用ASP.DLL解析ASP,可是始终没有找到资料,有待于研究,还有.NET。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebServer
{
    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;


    class Server
    {

        private TcpListener myListener;
        private int port = 8080; // 选者任何闲置端口

        //开始兼听端口
        //同时启动一个兼听进程
        public Server()
        {
            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()
        {
            Server MWS = new Server();
        }
        public void StartListen()
        {

            int iStartPos = 0;
            String sRequest;
            String sDirName;
            String sRequestedFile;
            String sErrorMessage;
            String sLocalDir;
            /注意设定你自己的虚拟目录/
            String sMyWebServerRoot = "E://MyWebServerRoot//"; //设置你的虚拟目录
            //
            String sFormattedMessage = "";
            String sResponse = "";
            string sPhysicalFilePath = "";

            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();
                }
            }
        }


    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388655.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

c#对文件的读写

最近需要对一个文件进行数量的分割&#xff0c;因为数据量庞大&#xff0c;所以就想到了通过写程序来处理。将代码贴出来以备以后使用。 //读取文件的内容 放置于StringBuilder 中 StreamReader sr new StreamReader(path, Encoding.Default); String line; StringBuilder sb …

php表格tr,jQuery+ajax实现动态添加表格tr td功能示例

本文实例讲述了jQueryajax实现动态添加表格tr td功能。分享给大家供大家参考&#xff0c;具体如下&#xff1a;功能&#xff1a;ajax获取后台返回数据给table动态添加tr/tdhtml部分&#xff1a;ajax部分&#xff1a;var year $(#year).val();//下拉框数据var province $(#prov…

maya的简单使用

1、导出obj类型文件window - settings preferences - plug- in Manager objExport.mllfile - export selection就有OBJ选项了窗口-设置/首选项- 插件管理 objExport.mll文件-导出当前选择2、合并元素在文件下面的下拉框&#xff0c;选择多边形。按住shift键&…

ai前沿公司_美术是AI的下一个前沿吗?

ai前沿公司In 1950, Alan Turing developed the Turing Test as a test of a machine’s ability to display human-like intelligent behavior. In his prolific paper, he posed the following questions:1950年&#xff0c;阿兰图灵开发的图灵测试作为一台机器的显示类似人类…

查看修改swap空间大小

查看swap 空间大小(总计)&#xff1a; # free -m 默认单位为k, -m 单位为M   total used free shared buffers cached  Mem: 377 180 197 0 19 110  -/ buffers/ca…

关于WKWebView高度的问题的解决

关于WKWebView高度的问题的解决 IOS端嵌入网页的方式有两种UIWebView和WKWebView。其中WKWebView的性能要高些;WKWebView的使用也相对简单 WKWebView在加载完成后&#xff0c;在相应的代理里面获取其内容高度&#xff0c;大多数网上的方法在获取高度是会出现一定的问题&#xf…

测试nignx php请求并发数,nginx 优化(突破十万并发)

一般来说nginx 配置文件中对优化比较有作用的为以下几项&#xff1a;worker_processes 8;nginx 进程数&#xff0c;建议按照cpu 数目来指定&#xff0c;一般为它的倍数。worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;为每个进…

多米诺骨牌v.1MEL语言

// // //Script Name:多米诺骨牌v.1 //Author:疯狂小猪 //Last Updated: 2011.10.5 //Email:wzybwj163.com // //---------------------------------------------------------------------------- //-----------------------------------------------------------------…

THINKPHP3.2视频教程

http://edu.51cto.com/lesson/id-24504.html lunix视频教程 http://bbs.lampbrother.net/read-htm-tid-161465.html TP资料http://pan.baidu.com/s/1dDCLFRr#path%252Fthink 微信开发&#xff0c;任务吧&#xff0c;留着记号了

mardown 标题带数字_标题中带有数字的故事更成功吗?

mardown 标题带数字统计 (Statistics) I have read a few stories on Medium about writing advice, and there were some of them which, along with other tips, suggested that putting numbers in your story’s title will increase the number of views, as people tend …

897. 递增顺序查找树-未解决

897. 递增顺序查找树 https://leetcode-cn.com/contest/weekly-contest-100/problems/increasing-order-search-tree/ package com.test;import java.util.ArrayList; import java.util.Collections; import java.util.List;/*** author stono* date 2018/9/2* 897. 递增顺序查…

Azure PowerShell (16) 并行开关机Azure ARM VM

《Windows Azure Platform 系列文章目录》 并行开机脚本&#xff1a; https://github.com/leizhang1984/AzureChinaPowerShell/blob/master/ARM/2StartAzureARMVM/StartAzureRMVM.txt 并行关机脚本&#xff1a; https://github.com/leizhang1984/AzureChinaPowerShell/blob/mas…

使用Pandas 1.1.0进行稳健的2个DataFrames验证

Pandas is one of the most used Python library for both data scientist and data engineers. Today, I want to share some Python tips to help us do qualification checks between 2 Dataframes.Pandas是数据科学家和数据工程师最常用的Python库之一。 今天&#xff0c;我…

Maya开发

Maya开发&#xff08;一&#xff09;-- 绪论 &#xff08;翻译自Maya官方文档&#xff09;2008-05-09 15:33 绪论 Autodesk Maya 是一个开放的产品,就是说任何Autodesk以外的人都可以改变Maya现有的特征,或者 增加新的特性.你可以用两个方法来修改MAYA: ME…

织梦在线报名平台php,DedeCMSv5

DedeCMS v5国内专业的PHP网站内容管理系统-织梦内容管理系统v5.8 Roadmap状态 ✅ 已完成 &#x1f528; 进行中 ❌ 未完成项目开发可以到织梦开发问题管理中进行交流反馈。&#x1f528; 调整DedeCMS目录结构&#xff0c;将原有include中外部访问的内容迁移出去&#xff1b;&am…

pom.xml文件详解

<project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd "> <!-- 父项目的坐…

软件工程第一次作业

&#xff08;1&#xff09;回想一下你初入大学时对计算机专业的畅想 当初你是如何做出选择计算机专业的决定的&#xff1f; 当初选择计算机专业是因为之前看大佬们参加信息竞赛&#xff0c;觉得很厉害、很有意思&#xff0c;而且也希望能自己做一款游戏出来&#xff0c;所以就选…

置信区间的置信区间_什么是置信区间,为什么人们使用它们?

置信区间的置信区间I’m going to try something a little different today, in which I combine two (completely unrelated) topics I love talking about, and hopefully create something that is interesting and educational.今天&#xff0c;我将尝试一些与众不同的东西…

事实上着就是MAYA4.5完全手册插件篇的内容

不过着好象侵权了&#xff0c;因为&#xff21;&#xff2c;&#xff29;&#xff21;&#xff33;声明不得一任何方式传播该手册的部分或全部_炙墨追零 Maya不为插件提供二进制兼容性。每当发布新版本时&#xff0c;旧插件的源代码要重新编译。然而&#xff0c;我们的目标是保…

制作alipay-sdk-java包到本地仓库

项目要用到支付宝的扫码支付&#xff0c;后台使用的maven 问了客服 官方目前没有 maven 的地址只能手动安装到本地了&#xff0c;如果建了maven 服务器也可以上传到服务器上 从支付宝官网上下载sdk 制作本地安装包 alipay-sdk-java.jar 放到D: 盘根目录下 执行命令&#xff1a…