C#创建一个小型Web Server(Socket实现)

来源(脚本之家)

From: http://www.jb51.net/article/106202.htm

C#创建一个小型Web Server(Socket实现)

作者:千一网络 字体:[增加 减小] 类型:转载 时间:2017-02-20

这篇文章主要介绍了关于C#利用Socket实现创建一个小型Web Server的相关资料,文中通过示例代码介绍的很详细,需要的朋友可以参考借鉴,下面来一起看看吧。

要实现了Web Server,通过以下几句代码浏览器访问就可以获得访问的数据。

Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketWatch.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 81));
socketWatch.Listen(20); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。

Thread thread = new Thread(delegate(object obj)
	{
		Socket socketListen = (Socket)obj;
		while (true)
		{
			Socket socket = socketListen.Accept();
			byte[] data = new byte[1024 * 1024 * 4]; // 浏览器发来的数据,限定为 4K。
			int length = socket.Receive(data, 0, data.Length, SocketFlags.None);
			socket.Send(Encoding.UTF8.GetBytes("欢迎访问 www.cftea.com\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
			socket.Shutdown(SocketShutdown.Both);
			socket.Close();
		}
});

thread.IsBackground = true;
thread.Start(socketWatch);


但以上只是原理,实际会很复杂,不过就算我们要做简单的 Web Server,还是需要解决两个问题:

一、输出 HTTP 头

byte[] body = Encoding.UTF8.GetBytes("欢迎访问 www.cftea.com\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
byte[] head = Encoding.UTF8.GetBytes(@"HTTP/1.1 200 OK
Content-Length: " + body.Length + @"
Content-Type: text/plain
Date: " + string.Format("{0:R}", DateTime.Now) + @"
Server: Cftea Web Server

");
socket.Send(head);
socket.Send(body);


只要有特定的格式,就会被浏览器当作 HTTP 头对待。HTTP 头的格式为:

第一行:HTTP/1.x + 空格 + 状态码 + 空格 + 描述

中间行:名称 + 冒号 + 空格(也可以省略) + 值

最后行:空行

格式一定要正确,否则影响浏览器对 HTTP 头和 HTTP 体的识别。

二、请求 HTTP 头

到目前为止,我们还不知道浏览器中输入的 URL 是什么呢。请求的 HTTP 头也是有特定格式的,我们只需要将其获取出来,进行拆解,就可以获取 URL 了。

拆解不是难事,我们说一说如何获取吧。前面的 data、length 不是一直没用么?如下:

string requestText = Encoding.UTF8.GetString(data, 0, length);


完整代码

Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketWatch.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 81));
socketWatch.Listen(20); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。

Thread thread = new Thread(delegate(object obj)
	{
		Socket socketListen = (Socket)obj;
		while (true)
		{
			using (Socket socket = socketListen.Accept())
			{
				byte[] data = new byte[1024 * 1024 * 4]; // 浏览器发来的数据
				int length = socket.Receive(data, 0, data.Length, SocketFlags.None);
				if (length > 0)
				{
					string requestText = Encoding.UTF8.GetString(data, 0, length);

					byte[] body = Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
					byte[] head = Encoding.UTF8.GetBytes(@"HTTP/1.1 200 OK
						Content-Length: " + body.Length + @"
						Content-Type: text/plain
						Date: " + string.Format("{0:R}", DateTime.Now) + @"
						Server: Cftea Web Server

					");
					socket.Send(head);
					socket.Send(body);
				}

				socket.Shutdown(SocketShutdown.Both);
				socket.Close();
			}
		}
});

thread.IsBackground = true;
thread.Start(socketWatch);


总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

原文链接:http://www.cftea.com/c/2017/02/6809.asp

如对本文有疑问,请提交到交流社区,广大热心网友会为你解答!! 点击进入社区

我对原作者的程序做了一些修改,迎合了自己的一些使用习惯,先谢谢原著的大神了

// socket-webserver-demo-1.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Windows.Forms;

class socket_webserver_demo1 : Form {

	protected override System.Drawing.Size DefaultSize{
		get{
			return new System.Drawing.Size(600, 200);
		}
	}

	public webserver_demo1(){

		this.Text = "socket_webserver_demo1.cs (WebServer 127.0.0.1:81)";
		this.StartPosition = FormStartPosition.CenterScreen;

		Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		socketWatch.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 81));
		socketWatch.Listen(5); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。

		Thread thread = new Thread(
			delegate(object obj){
				Socket socketListen = (Socket)obj;
				while (true){
					Socket socket = socketListen.Accept();
					byte[] data = new byte[1024 * 1024 * 4]; // 浏览器发来的数据,限定为 4K。
					int length = socket.Receive(data, 0, data.Length, SocketFlags.None);
					byte[] body = Encoding.UTF8.GetBytes("欢迎访问 www.cftea.com\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") );
					byte[] head = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\n" +
						"Server: WebServer.C#\r\n" +
						"Content-Type: text/plain; charset=utf-8\r\n" +
						"Content-Length: " + body.Length + "\r\n\r\n");
					socket.Send(head);
					socket.Send(body);
					socket.Shutdown(SocketShutdown.Both);
					socket.Close();
				}
			});

		thread.IsBackground = true;
		thread.Start(socketWatch);
	}

	public static void Main(string[] args){
		Application.Run(new socket_webserver_demo1());
	}
}


编译用的 bat 文件

@echo off
rem socket-webserver-demo-1-cs--builder.bat

set strLinker=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\csc.exe
set strAppName=socket-webserver-demo-1

echo %strLinker%
echo.

%strLinker% /target:winexe %strAppName%.cs

pause


再次改进,稳定性提升了一些

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Windows.Forms;

class socket_webserver_demo1 : Form {

	protected override System.Drawing.Size DefaultSize{
		get{
			return new System.Drawing.Size(600, 200);
		}
	}

	public socket_webserver_demo1(){

		this.Text = "socket_webserver_demo1.cs (WebServer 0.0.0.0:8002)";
		this.StartPosition = FormStartPosition.CenterScreen;

		Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		socketWatch.Bind(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8002));
		socketWatch.Listen(5); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。

		Thread thread = new Thread(
			delegate(object obj){
				Socket socketListen = (Socket)obj;
				while (true){
					try{
						Console.WriteLine("Ready...................................");
						Socket socket = socketListen.Accept();
						byte[] data = new byte[1024 * 4]; // 浏览器发来的数据,限定为 4K。
						int length = socket.Receive(data, 0, data.Length, SocketFlags.None);

						bool isRequestIndex = (data[5] == 32);

						int l;
						for(l = 0; l < 4096; l++){
							if(data[l] == 0) break;
						}

						byte[] bytesRequest = new byte[l];
						System.Buffer.BlockCopy(data, 0, bytesRequest, 0, l);
						string strRequest = System.Text.Encoding.Default.GetString( bytesRequest );
						Console.WriteLine("Request Length: " + l + " ......");
						Console.WriteLine(strRequest);

						string strResponse;

						if(isRequestIndex){

							// byte[] body = Encoding.UTF8.GetBytes("<html>\n<head><title>From Socket WebServer</title></head>\n" +
							// 	"<body>\n<h1>Hello socket.</h1>\n<p>" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +
							// 	"</p>\n</body>\n</html>");

							// Console.WriteLine(body.Length);

							// byte[] head = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\n" +
							// 	"Server: WebServer.C#\r\n" +
							// 	"Content-Type: text/html; charset=utf-8\r\n" +
							// 	"Content-Length: " + body.Length + "\r\n\r\n");

							// socket.Send(head);
							// socket.Send(body);

							strResponse = "HTTP/1.1 200 OK\r\n" +
								"Server: WebServer.C#\r\n" +
								"Content-Type: text/html; charset=utf-8\r\n" +
								"Content-Length: 133\r\n\r\n" +
								"<html>\n<head><title>From Socket WebServer</title></head>\n" +
								"<body>\n<h1>Hello socket.</h1>\n<p>" +
								DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +
								"</p>\n</body>\n</html>";

						}else{

							strResponse = "HTTP/1.1 404 Not Found\r\n" +
								"Server: WebServer.C#\r\n" +
								"Content-Type: text/html; charset=utf-8\r\n" +
								"Content-Length: 3\r\n\r\n404";

						}

						socket.Send( Encoding.UTF8.GetBytes(strResponse) );
						Console.WriteLine( strResponse );

						socket.Shutdown(SocketShutdown.Both);
						socket.Close();
						
						Console.WriteLine("Succeed.................................\n");

					}catch(Exception e){

						Console.WriteLine(e);

					}
				}
			});

		thread.IsBackground = true;
		thread.Start(socketWatch);
	}

	public static void Main(string[] args){
		Application.Run(new socket_webserver_demo1());
	}
}

Link: http://www.asm32.net/article_details.aspx?id=7258


浏览次数 0 发布时间 2017-08-05 01:05:31 从属分类 C# 【评论】【 】【打印】【关闭
 
| www.asm32.net | 2006版 | 资料中心 | linux | asm/asm32 | C/C++ | VC++ | java | Python | 书签 | ASP.Net书签 | 京ICP备09029108号-1