簡體   English   中英

Web服務器:從流中讀取http請求

[英]Web server: reading http request from stream

問候!

我一直在鬼混C#(現在),現在我堅持使用簡單的HTTP Web服務器實現。 老實說,我不想與HTTP規范相處-我只需要編寫一個很小的 (讀作簡單的 )HTTP Web服務器。 而且我鼓勵了這個問題:客戶端將請求發送到服務器,然后服務器解析它,運行一些操作,建立響應並將其發送回客戶端。 這似乎是顯而易見的(至少對我而言)。

這是到目前為止我得到的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 80);
            listener.Start();

            Socket sock = listener.AcceptSocket();

            try
            {
                Stream s = new NetworkStream(sock);
                s.ReadTimeout = 300;

                StreamReader reader = new StreamReader(s);
                StreamWriter writer = new StreamWriter(s);
                writer.AutoFlush = true;

                Console.WriteLine("Client stream read:\r\n");

                string str = "none";

                while (sock.Connected && !reader.EndOfStream && str.Length > 0) // here's where i'm stuck
                {
                    str = reader.ReadLine();
                    Console.WriteLine("{0} ({1})", str, str.Length);
                }

                Console.WriteLine("Sending response...\r\n");

                {
                    string response = "<h1>404: Page Not Found</h1>";
                    writer.WriteLine("HTTP / 1.1 404 Not Found");
                    writer.WriteLine("Content-Type: text/html; charset=utf-8");
                    writer.WriteLine("Content-Length: {0}", response.Length);
                    writer.WriteLine("\r\n{0}", response);
                }

                Console.WriteLine("Client: over\r\n");

                s.Close();
                sock.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}\r\nTrace: \r\n{1}", e.Message, e.StackTrace);
            }

            Console.ReadKey();
        }
    }
}

但是我遇到了一個“難題”:我正在通過輸入流讀取請求,因此當客戶端關閉瀏覽器中的頁面時,輸入數據流將終止(讓我們談談最明顯的動作,不包括curl,w3和其他“怪胎的東西“)。

因此,問題是:如何確定請求的結束? 例如,我什么時候應該停止讀取請求數據並開始發送響應?

為什么不使用HttpListener? 您可以使用5行代碼來構建一個簡單的HTTP服務器。

這篇Wikipedia文章非常簡潔地說明了請求消息格式。

請求行和標頭必須全部以<CR> <LF>結尾(即,回車后跟換行符)。 空行只能由<CR> <LF>組成,不能包含其他空格。 在HTTP / 1.1協議中,除Host以外的所有標頭都是可選的。

基本上,請注意標題和/或潛在郵件正文之后的空白行。

根據HTTP規范 ,可以使用某些標頭來確定是否存在消息正文:

通過在請求的消息頭中包含Content-Length或Transfer-Encoding頭字段,可以指示請求中消息主體的存在。

另一個選擇是: http : //webserver.codeplex.com/即使您不想使用它,也可以竊取想法,因為它實現了完整的請求生命周期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM