C#建立最简单的web服务,无需IIS

本程序只是入门级程序,所以不考虑

1,多线程。

2,安全性。

3,不考虑端点下载文件。

4,Keep-Alive。

5,不考虑head。

6,为了简洁,删掉了catch的内容。

exe的祖父目录必须有wwwroot文件夹,且文件夹有index.htm,内容不限。 

开发环境: WinXP+VS2010C#

一,新建一个项目TestWeb,项目类型:Windows窗口应用程序。

二,新建类RequestProcessor。

using System;

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

using System.Diagnostics;

namespace TestWeb

{

class RequestProcessor

{

public bool ParseRequestAndProcess(string[] RequestLines)//解析内容

{

for (int i = 0; i < RequestLines.Length; i++)

System.Diagnostics.Trace.Write(RequestLines[i]);

char[] sp = new Char[1] { ‘ ‘ };

string[] strs = RequestLines[0].Split(sp);

if (strs[0] == "GET")

{

Send(strs[1], 0, 0);

}

return false;

}

void Send(string filename, long start, long length)//发送文件(文件头和文件)

{

string strFileName = GetPathFileName(filename);

FileStream fs = null;

try

{

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

}

catch (IOException)// FileNotFoundException)

{//不能将 e.Message,发给浏览器,否则会有安全隐患的

SendHeadrAndStr("打开文件" + filename + "失败。");

return;

}

if (length == 0)

length = fs.Length - start;

SendHeader("text/html", (fs.Length == length), start, length);

sendContent(fs, start, length);

}

public void SendHeadrAndStr(String str)//直接将str的内容发给html

{

byte[] sendchars = Encoding.Default.GetBytes((str).ToCharArray());

SendHeader("text/html", true, 0, sendchars.Length);

SendStr(Encoding.Default, str);

}

private void SendHeader(string fileType, bool bAll, long start, long length)//发送文件头

{

try

{

Encoding coding = Encoding.Default;

string strSend;

string strState = (bAll) ? "HTTP/1.1 200 OK" : "HTTP/1.1 206 Partial Content";

SendStr(coding, strState + "\r\n");

SendStr(coding, "Date: \r\n");

SendStr(coding, "Server: httpsrv/1.0\r\n");

SendStr(coding, "MIME-Version: 1.0\r\n");

SendStr(coding, "Content-Type: " + fileType + "\r\n");

strSend = "Content-Length: " + length.ToString();

SendStr(coding, strSend + "\r\n");

//发送一个空行

SendStr(coding, "\r\n");

}

catch (ArgumentException)//the request is WRONG

{

}

}

private void sendContent(FileStream fs, long start, long length)//发生文件内容

{

try

{

//报文头发送完毕,开始发送正文

const int SOCKETWINDOWSIZE = 8192;

long r = SOCKETWINDOWSIZE;

int rd = 0;

Byte[] senddatas = new Byte[SOCKETWINDOWSIZE];

fs.Seek(start, SeekOrigin.Begin);

do

{

r = start + length - fs.Position;

//fs.BeginRead(s,s,s,s,d) 以后使用的版本,用以提高读取的效率

if (r >= SOCKETWINDOWSIZE)

rd = fs.Read(senddatas, 0, SOCKETWINDOWSIZE);

else

rd = fs.Read(senddatas, 0, (int)r);

mSockSendData.Send(senddatas, 0, rd, SocketFlags.None);

} while (fs.Position != start + length);

}

catch (SocketException e)

{

throw e;

}

catch (IOException e)

{

throw e;

}

}

public Socket mSockSendData;//Notice: get from ClientSocketThread.s

private string GetPathFileName(string filename)

{

const string strDefaultPage = "index.htm";

const string strWWWRoot = "..\\..\\wwwroot\\";

string strFileName = String.Copy(filename);

if ("/" == strFileName)

strFileName = strDefaultPage;

return System.AppDomain.CurrentDomain.BaseDirectory + strWWWRoot + strFileName;

}

private void SendStr(Encoding coding, string strSend)//发送一个字符串

{

Byte[] sendchars = new Byte[512];

sendchars = coding.GetBytes((strSend).ToCharArray());

mSockSendData.Send(sendchars, 0, sendchars.Length, SocketFlags.None);

}

}

}

三,新建类ClientSocketThread。

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

namespace TestWeb

{

class ClientSocketThread

{

public TcpListener tcpl;//Notice: get from SrvMain.tcpl

private static Encoding ASCII = Encoding.ASCII;

public void HandleThread()

{

Thread currentThread = Thread.CurrentThread;

try

{

Socket s = tcpl.AcceptSocket();

RequestProcessor aRequestProcessor = new RequestProcessor(); //Notice:

aRequestProcessor.mSockSendData = s;//Notice: so that the processor can work

const int BUFFERSIZE = 4096;//that‘s enough???

Byte[] readclientchar = new Byte[BUFFERSIZE];

char[] sps = new Char[2] { ‘\r‘, ‘\n‘ };

string[] RequestLines = new string[32];

do

{

//use BUFFERSIZE contral the receive data size to avoid the BufferOverflow attack

int rc = s.Receive(readclientchar, 0, BUFFERSIZE, SocketFlags.None);

string strReceive = ASCII.GetString(readclientchar, 0, rc);

RequestLines = strReceive.Split(sps);

} while (aRequestProcessor.ParseRequestAndProcess(RequestLines));

s.Close();

}

catch (SocketException)

{

}

}

}

}

四,主对话框中增加按钮,按键的相应函数加如下代码。

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Threading;

namespace TestWeb

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

try

{

//启动监听程序

TcpListener tcpl;

IPAddress LocalIP = Dns.Resolve("localhost").AddressList[0];

tcpl = new TcpListener(LocalIP, 80); // listen on port 80

tcpl.Start();

// int ThreadID = 0;

while (true)

{

while (!tcpl.Pending())

{

Thread.Sleep(100);

}

//启动接受线程

ClientSocketThread myThreadHandler = new ClientSocketThread();

myThreadHandler.tcpl = tcpl;//Notice: dont forget do this

ThreadStart myThreadStart = new ThreadStart(myThreadHandler.HandleThread);

Thread myWorkerThread = new Thread(myThreadStart);

myWorkerThread.Start();

}

}

catch (SocketException )

{

}

catch (FormatException)

{

}

catch (Exception )

{

}

//  Console.Read();

}

}

}

五,启动TestWeb.exe,并单击主对话框上的按钮。在浏览器中输入:http://127.0.0.1/ 或http://127.0.0.1:80。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-12-13 19:55:25

C#建立最简单的web服务,无需IIS的相关文章

建立基于https的web服务

先安装openssl [[email protected] ~]# yum install openssl 搭建私有CA服务器 修改openssl.cnf配置文件 [[email protected] ~]# vim /etc/pki/tls/openssl.cnf dir=/etc/pki/CA 创建相关的文件 [[email protected] ~]# cd /etc/pki/CA [[email protected] ~]# makdir certs newcerts crl [[ema

ASP网站建立不成功是因为 web服务扩展没有设置好

ASP网站建立不成功是因为 web服务扩展没有设置好 原文地址:https://blog.51cto.com/215363/2446865

Web服务器之iis,apache,tomcat三者之间的比较

IIS-Apache-Tomcat的区别 IIS与Tomcat的区别 IIS是微软公司的Web服务器.主要支持ASP语言环境. Tomcat是Java Servlet 2.2和JavaServer Pages 1.1技术的标准实现,是基于Apache许可证下开发的SJP语言环境容器,严格得说不能算是一个WEB服务器,而是Apache服务适配器. tomcat主要的任务不是WEB服务,而是支持JSP语言环境. IIS就是也款WEB服务器,支持ASP语言环境 Apache与Tomcat的区别 APA

python第三方库系列之十六--建立最简单的web服务器

利用Python自带的包可以建立简单的web服务器.在DOS里cd到准备做服务器根目录的路径下,输入命令: python -m Web服务器模块 [端口号,默认8000] 例如: python -m SimpleHTTPServer 8080 然后就可以在浏览器中输入 http://localhost:端口号/路径 来访问服务器资源. 例如: http://localhost:8080/index.htm(当然index.htm文件得自己创建) 其他机器也可以通过服务器的IP地址来访问. 这里的

学习用node.js建立一个简单的web服务器

一.建立简单的Web服务器涉及到Node.js的一些基本知识点: 1.请求模块 在Node.js中,系统提供了许多有用的模块(当然你也可以用JavaScript编写自己的模块,以后的章节我们将详细讲解),如http.url等.模块封装特定的功能,提供相应的方法或属性,要使用这些模块,需要先请求模块获得其操作对象. 例如要使用系统的http模块,可以这样写: var libHttp = require('http'); //请求HTTP协议模块 这样,以后的程序将可以通过变量libHttp访问ht

【转】用Python建立最简单的web服务器

利用Python自带的包可以建立简单的web服务器.在DOS里cd到准备做服务器根目录的路径下,输入命令: python -m Web服务器模块 [端口号,默认8000] 例如: python -m SimpleHTTPServer 8080 然后就可以在浏览器中输入 http://localhost:端口号/路径 来访问服务器资源. 例如: http://localhost:8080/index.htm(当然index.htm文件得自己创建) 其他机器也可以通过服务器的IP地址来访问. 这里的

基于gin框架搭建的一个简单的web服务

刚把go编程基础知识学习完了,学习的时间很短,可能还有的没有完全吸收.不过还是在项目中发现知识,然后在去回顾已学的知识,现在利用gin这个web框架做一个简单的CRUD操作. 1.Go Web框架的技术选型 Top 6 web frameworks for Go as of 2017,可以看看这个go语言中Web框架的对比和老大的推荐,我选择gin框架作为学习go语言的框架. image.png 2.Gin介绍 gin框架的中文文档,这个文档相当好,清晰明了解释gin框架的整个用法.下面是gin

Python 最简单的web服务

python -m SimpleHTTPServer  8321   1.python 没有指定目录的参数 想启动目录 就cd到该目录下 2.在目录下创建一个index.html 3.启动web服务,(端口被占用会报错的)    

建立自己的网站Web服务

一.建立属于自己的网站,做一些内容.二.进入你的控制面板我们开始做网站 点击我们的Windows 管里工具,选择我们的服务器信息 下面就是你的地址: 验证一下我们用其他电脑去登陆这个地址,如果登陆不了关闭你虚拟机或者是你本机的防火墙.我们要添加网页的东西,首先我们回到我们的网络工具里查看. 我们去找到这个文件夹在哪儿 我们新建一个文本文档输入我们的内容 下面我们来更改我们文件的扩展名,如果更改不了,就到我的电脑,选择工具,选择文件夹属性-查看-隐藏文件类型的扩展名,把这个勾去掉.我们用其他电脑或