c# - 网络服务器 : reading http request from stream

标签 c# .net http

您好!

我(再次)一直在使用 C#,现在我坚持使用简单的 HTTP Web 服务器实现。老实说,我不想遵守 HTTP 规范 - 我只需要编写一个非常微型(读作简单)的 HTTP 网络服务器。我鼓励这个问题:客户端向服务器发送请求,然后服务器解析它,运行一些操作,构建响应并将其发送回客户端。这似乎是显而易见的(至少对我而言)。

这是我到目前为止所得到的:

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();
        }
    }
}

但是我遇到了一个“水下石头”:我正在通过输入流读取请求,所以当客户端在他的浏览器中关闭页面时,输入数据流将被终止(让我们谈谈最明显的 Action ,不包括 curl,w3和其他“极客的东西”)。

那么,问题来了:如何判断请求结束?例如。我应该什么时候停止读取请求数据并开始发送响应?

最佳答案

为什么不用HttpListener?您可以在 5 行代码中拥有一个简单的 HTTP 服务器。

关于c# - 网络服务器 : reading http request from stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4715896/

相关文章:

c# - 在 C# 中使用重载的 VB.NET Not 运算符

c# - 忽略鼠标点击并将键盘输入发送到外部应用程序

c# - dotTrace 在 PipelineRuntime.ProcessRequestNotification 中显示大量时间不明

java - 露天休息,文件上传: cannot set description and filename

c# - 检查异常类型性能

c# - 选择要在 Visual Studio 2010 中调试或运行的解决方案下的项目

c# - 通过TCP连接到多个客户端的服务

C#如何Regex.Replace "\r\n"(实际字符,不是换行符)

http - 用于开发 RESTful Web 服务的工具

http - 为什么我不能在 Go 中编写来自单独包的 HTTP 响应?