最基本的Web服务器(C#实现)

     要实现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;
                }
            }
        }
    }

后台提示



浏览器显示


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值