본문 바로가기
C# /WindowsForm

HttpListener를 이용한 Simple한 Web서버 구현 예제

by Hwoarang757 2022. 8. 18.

출처 : https://gist.github.com/define-private-public/d05bc52dd0bed1c4699d49e2737e80e7

 

A Simple HTTP server in C#

A Simple HTTP server in C#. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

  public class HttpListenerWebServer
    {
        private HttpListener listner;
        private string url = string.Empty;
        private int requestCount = 0;
        private FormTray myTrayForm = null;
        public HttpListenerWebServer(int port , FormTray myTrayForm)
        {
            this.url = string.Format("http://localhost:{0}/", port);
            this.myTrayForm = myTrayForm;

        }

        public async void StartHttpServer()
        {
            await Task.Run(() => { 
                listner = new HttpListener();
                listner.Prefixes.Add(url);
                listner.Start();

                HandleIncomingConnections().GetAwaiter().GetResult();
                
                listner.Close();
            });
        }


        public async Task HandleIncomingConnections()
        {
            bool runServer = true;

            while(runServer)
            {
                HttpListenerContext ctx = await listner.GetContextAsync();

                HttpListenerRequest req = ctx.Request;
                HttpListenerResponse resp = ctx.Response;

                Console.WriteLine(string.Format("Request # : {0}", ++requestCount));
                Console.WriteLine(req.Url.ToString());
                Console.WriteLine(req.RawUrl.ToString());
                Console.WriteLine(req.HttpMethod);
                Console.WriteLine(req.UserHostName);
                Console.WriteLine(req.UserAgent);

                string rawUrl = req.RawUrl.ToString().CheckNull().IndexOf("/") != -1 && req.RawUrl.ToString().CheckNull().Length > 1 ?
                                req.RawUrl.Substring(req.RawUrl.ToString().CheckNull().IndexOf("/") + 1) :
                                req.RawUrl.ToString();

                Console.WriteLine(rawUrl);

                using (StreamReader streamReader = new StreamReader(req.InputStream, req.ContentEncoding))
                {
                    if (rawUrl.ToUpper().Contains("CMD=OPEN"))
                        ParsePostStrContents(streamReader.ReadToEnd());
                }
                byte[] respByte = Encoding.Default.GetBytes("{\"result\":\"0\",\"msg\":\"OK\"}");
                resp.ContentType = "text/html";
                resp.ContentEncoding = Encoding.Default;
                resp.ContentLength64 = respByte.Length;
                resp.Headers.Add("Access-Control-Allow-Origin","*");

                resp.OutputStream.Write(respByte, 0 , respByte.Length);
                resp.Close();

                myTrayForm.FaxCommandHandler(rawUrl);
            }

        }



    /// <summary>
    /// 2022.06.13 김영대 추가 진행 
    /// </summary>
    /// <param name="strReceived"></param>
    private void ParsePostStrContents(string strReceived)
    {
        string methodName = MethodBase.GetCurrentMethod().Name;
        try
        {

            NameValueCollection nameValue = System.Web.HttpUtility.ParseQueryString(strReceived);

            if (nameValue.Get("userid") != null)
            {

                MyApplication.g_UserSession.userid = nameValue.Get("userid");
                MyApplication.g_UserSession.usernm = nameValue.Get("usernm");
                MyApplication.g_UserSession.departmentid = nameValue.Get("departmentid");
                MyApplication.g_UserSession.loginid = nameValue.Get("loginid");
                MyApplication.g_UserSession.deptnm = nameValue.Get("deptnm");
                MyApplication.g_UserSession.authoritycd = nameValue.Get("authoritycd");
                MyApplication.g_UserSession.authoritynm = nameValue.Get("authoritynm");

                Utility.WriteLog(string.Format("{0} Get Post Param USERID={1}\n", methodName, nameValue.Get("userid")), MyApplication.g_logwriteyn);
                Debug.WriteLine(string.Format("userid={0},usernm={1},departmentid={2},loginid={3},deptnm={4},authoritycd={5},authoritynm={6}",
                                               MyApplication.g_UserSession.userid,
                                               MyApplication.g_UserSession.usernm,
                                               MyApplication.g_UserSession.departmentid,
                                               MyApplication.g_UserSession.loginid,
                                               MyApplication.g_UserSession.deptnm,
                                               MyApplication.g_UserSession.authoritycd,
                                               MyApplication.g_UserSession.authoritynm
                                ));
            }
        }
        catch (Exception exception)
        {
         
        }
    }