簡單搭建http服務器-HttpListener使用

使用HTTPListener能夠簡單搭建一個Http服務器,對於本地使用非常方面,想起以前使用了WebSocket來與本地網頁通信的例子,也是能夠改成使用HTTPListener來作的。看下HTTPListener的使用吧。c#

public class RJHttp
    {
        private HttpListener httpListener = new HttpListener();
        public RJHttp()
        {
            this.httpListener.Prefixes.Add("http://127.0.0.1:8089/");//必須以/結尾
            this.httpListener.Start();
            ///異步等待請求
            this.httpListener.BeginGetContext(this.Read, this.httpListener);
        }
        private void Read(IAsyncResult result)
        {
            ///獲取到請求
            HttpListenerContext context = this.httpListener.EndGetContext(result);
            ///獲取請求的數據
            HttpListenerRequest request = context.Request;
            string contentType = request.ContentType;
            string httpMethod = request.HttpMethod;
            string userAgent = request.UserAgent;
            StreamReader sr = new StreamReader(request.InputStream);
            string code = sr.ReadToEnd();
            ///返回數據
            byte[] bys = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
            context.Response.OutputStream.Write(bys, 0, bys.Length);
            context.Response.Close();
            this.httpListener.BeginGetContext(this.Read, this.httpListener);
        }
    }

對於請求端使用的什麼請求方式能夠使用request.HttpMethod的值進行判斷,而後返回指定的數據便可。服務器

相關文章
相關標籤/搜索