admin 管理员组文章数量: 887021
2024年1月10日发(作者:java代码列传)
namespace { public class HttpProcessor { public TcpClient socket;
public HttpServer srv; private Stream inputStream; public StreamWriter outputStream; public String http_method; public String http_url; public String http_protocol_versionstring; public Hashtable httpHeaders = new Hashtable(); private static int MAX_POST_SIZE = 10 * 1024 * 1024; // 10MB public HttpProcessor(TcpClient s, HttpServer srv) { = s; = srv;
}
private string streamReadLine(Stream inputStream) { int next_char; string data = ""; while (true) { next_char = te(); if (next_char == 'n') { break; } if (next_char == 'r') { continue; } if (next_char == -1) { (1); continue; }; data += (next_char); }
return data; } public void process() {
// we can't use a StreamReader for input, because it buffers up extra data on us inside it's // "processed" view of the world, and we want the data raw after the headers inputStream = new BufferedStream(eam()); // we probably shouldn't be using a streamwriter for all output from handlers either outputStream = new StreamWriter(new BufferedStream(eam())); try { parseRequest(); readHeaders(); if (http_("GET")) { handleGETRequest(); } else if (http_("POST")) { handlePOSTRequest(); } } catch (Exception e) { ine("Exception: " + ng()); writeFailure(); } (); // (); // flush any remaining output inputStream = null; outputStream = null; // bs = null;
();
} public void parseRequest() { String request = streamReadLine(inputStream); string[] tokens = (' '); if ( != 3) { throw new Exception("invalid http request line"); } http_method = tokens[0].ToUpper(); http_url = tokens[1]; http_protocol_versionstring = tokens[2]; ine("starting: " + request); } public void readHeaders() { ine("readHeaders()"); String line; while ((line = streamReadLine(inputStream)) != null) { if (("")) { ine("got headers"); return; }
int separator = f(':'); if (separator == -1) {
throw new Exception("invalid http header line: " + line); } String name = ing(0, separator); int pos = separator + 1; while ((pos < ) && (line[pos] == ' ')) { pos++; // strip any spaces }
string value = ing(pos, - pos); ine("header: {0}:{1}",name,value); httpHeaders[name] = value; } } public void handleGETRequest() { GETRequest(this); } private const int BUF_SIZE = 4096; public void handlePOSTRequest() { // this post data processing just reads everything into a memory stream. // this is fine for smallish things, but for large stuff we should really // hand an input stream to the request processor. However, the input stream
// we hand him needs to let him see the "end of the stream" at this content
// length, because otherwise he won't know when he's seen it all!
ine("get post data start"); int content_len = 0; MemoryStream ms = new MemoryStream(); if (nsKey("Content-Length")) { content_len = 32(aders["Content-Length"]); if (content_len > MAX_POST_SIZE) { throw new Exception( ("POST Content-Length({0}) too big for this simple server", content_len)); } byte[] buf = new byte[BUF_SIZE];
int to_read = content_len; while (to_read > 0) {
ine("starting Read, to_read={0}",to_read); int numread = (buf, 0, (BUF_SIZE, to_read)); ine("read finished, numread={0}", numread); if (numread == 0) { if (to_read == 0) { break; } else { throw new Exception("client disconnected during post"); } } to_read -= numread; (buf, 0, numread); } (0, ); } ine("get post data end"); POSTRequest(this, new StreamReader(ms)); } public void writeSuccess() { ine("HTTP/1.0 200 OK");
ine("Content-Type: text/html;charset=utf-8"); ine("Connection: close"); ine(""); } public void writeFailure() { ine("HTTP/1.0 404 File not found"); ine("Connection: close"); ine(""); } } public abstract class HttpServer { protected int port; TcpListener listener; bool is_active = true;
public HttpServer(int port) { = port; }
public void listen() { listener = new TcpListener(port); (); while (is_active) {
TcpClient s = TcpClient(); HttpProcessor processor = new HttpProcessor(s, this); Thread thread = new Thread(new ThreadStart(s)); (); (1); } } public abstract void handleGETRequest(HttpProcessor p); public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData); } public class MyHttpServer : HttpServer { public MyHttpServer(int port) : base(port) { } public override void handleGETRequest(HttpProcessor p) { ine("request: {0}", _url); uccess(); ine("
test server
"); ine("Current Time: " + ng()); ine("url : {0}", _url); ine(""); } public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) { ine("POST request: {0}", _url); string data = End(); ine("test server
"); ine("return"); ine("postbody:
{0}", data);
} } public class TestMain { public static int Main(String[] args) { HttpServer httpServer; if (gth(0) > 0) { httpServer = new MyHttpServer(16(args[0])); } else { httpServer = new MyHttpServer(8080); } Thread thread = new Thread(new ThreadStart()); (); return 0; } }}
版权声明:本文标题:C#实现一个最简单的HTTP服务器 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/free/1704844177h464020.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论