日期:2014-05-18 浏览次数:21543 次
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; using System.Text.RegularExpressions; namespace WebServer { class HttpProcess { Socket s; public HttpProcess(Socket s) { this.s = s; } public void process() { string head = ""; int len = 0; byte[] buf = new byte[1]; do { len = s.Receive(buf); head += Encoding.ASCII.GetString(buf); } while (len > 0 && !head.EndsWith("\r\n\r\n")); Console.WriteLine(head); string content = "ok"; string raw = string.Format(@"HTTP/1.1 200 OK Content-Length: {0} Content-Type: text/html {1}", Encoding.Default.GetByteCount(content), content); Console.WriteLine(raw); s.Send(Encoding.Default.GetBytes(raw)); s.Shutdown(SocketShutdown.Both); s.Close(); } } public class HttpServer { static void listen() { Socket listener = new Socket(0, SocketType.Stream, ProtocolType.Tcp); IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 81); listener.Bind(endpoint); listener.Blocking = true; listener.Listen(-1); while (true) { Socket s = listener.Accept(); HttpProcess p = new HttpProcess(s); Thread thread = new Thread(new ThreadStart(p.process)); thread.Start(); } } public static int Main(String[] args) { Thread thread = new Thread(new ThreadStart(listen)); thread.Start(); return 0; } } }