简单的 Web 服务器 C#
本文关键字:服务器 Web 简单 | 更新日期: 2023-09-27 17:56:51
我需要一些关于这段代码的帮助:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace HttpEcho
{
class HttpEchoProgram
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Waiting for Client...");
TcpClient newConn = server.AcceptTcpClient();
IPEndPoint iep = (IPEndPoint)(newConn.Client.RemoteEndPoint);
IPAddress add = iep.Address;
int prt = iep.Port;
Console.WriteLine("Connected with a client: {0}: {1} ", add, prt);
NetworkStream stream = newConn.GetStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine("HTTP/1.1 200 OK");
sw.WriteLine("Content-Type: text/plain");
//sw.WriteLine("Content-Length: size");
sw.WriteLine();
String line = null;
while ((line = sr.ReadLine()).Length != 0)
{
Console.WriteLine(line);
sw.WriteLine(line);
sw.Flush();
}
newConn.Close();
server.Stop();
}
}
}
我想修改此代码,以便它可以用作简单的 Web 服务器,它在本地文件系统中获取请求的页面并将其返回到浏览器。
您可以通过从 HttpListener 开始为自己节省几千行代码。 http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx