要实现Web服务器,就必须先了解HTTP协议。了解浏览器是如何通过HTTP协议与服务器进行通信的,把这些问题搞懂后,那Web服务器的框架就有了。
后台提示
我们所实现的是一个最基础的。不管用户发送何种请求,都返回一个页面,至少演示一下HTTP工作的流程。HTTP协议默认是80端口。所以一般浏览器发起请求时都没有显式的将端口放在地址里面。其实就可以看成是一次通信,有IP地址,有端口(80)。服务器和浏览器收到数据后都进行解析,完成各自规定的动作。这就是HTTP协议。我们这里用的是8080端口,IP是127.0.0.1,接收到请求后,直接返回状态和网页信息(HTML格式)。后面会将它逐步完善,能实现大部分的功能。代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace http_server
{
class Program
{
static void Main(string[] args)
{
int len;
int port = 8080;//端口
byte[] buf = new byte[1024];
//IP是本地127.0.0.1
TcpListener server = new TcpListener(IPAddress.Any, port);
server.Start();
Console.WriteLine("服务运行在[{0}]端口", port);
while (true)
{
Socket clent = server.AcceptSocket();
len = clent.Receive(buf);
Console.WriteLine("收到 [{0}] 数据", len);
Console.WriteLine(Encoding.ASCII.GetString(buf));
string ss = "HTTP/1.0 200 OK\nContent-Type:text/html\n\n Welcome!<br>Now Time:{0}";
string ss1 = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>My Home</title></head><body><h2>Web Server System</h2></body></html>";
DateTime dt = DateTime.Now;
string nn = string.Format(ss, dt.ToString());
len = clent.Send(Encoding.ASCII.GetBytes(nn));
clent.Send(Encoding.ASCII.GetBytes(ss1));
Console.WriteLine("发送 [{0}] 数据", len);
Console.WriteLine(ss);
clent.Close();
clent = null;
}
}
}
}
后台提示
浏览器显示