Reply To: Webserver

HomeForumsMonoBrick EV3 FirmwareWebserverReply To: Webserver

#5164
Author Image
Jacek S
Participant

Hi Again,

I have created own simple HTTP server. Now I have great performance :)


    class Program
    {
        static void Main(string[] args)
        {
            HttpListener httpListener = new HttpListener();
            httpListener.Prefixes.Add("http://*:9090/");
            httpListener.Start();
            var run = true;
            (new ButtonEvents()).EscapePressed += () => run = false;
            while (run)
            {
               var context = httpListener.GetContext();
               Process(context);
            }
        }

        public static string RootPath
        {
            get
            {
                string filePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
                return Path.GetDirectoryName(filePath) + "/" ;
            }
        }

        static string GetContentType(string ext)
        {
            switch (ext.ToLower())
            {
                case ".js":
                    return "text/javascript";
                case ".htm":
                case ".html":
                    return "text/html";
                case ".png":
                    return "image/png";
                case ".jpg":
                    return "image/jpg";
                case ".css":
                    return "text/css";

                default:
                    return "application/octet-stream";
            }
        }

        private static void Process(HttpListenerContext context)
        {
            string reqPath = context.Request.Url.AbsolutePath;
            //Console.WriteLine(reqPath);
            if (reqPath == "/truck/joypos")
            {
                context.Response.StatusCode = 200;
                context.Response.Close();
                return;
            }
            reqPath = Path.Combine(RootPath, reqPath.Substring(1));
            if (!File.Exists(reqPath))
            {
                context.Response.StatusCode = 404;
                context.Response.Close();
                return;
            }
            var contentType = GetContentType(Path.GetExtension(reqPath));
            context.Response.Headers[HttpResponseHeader.ContentType] = contentType;
            var content = File.ReadAllBytes(reqPath);
            context.Response.OutputStream.Write(content, 0, content.Length);
            context.Response.Close();
        }
    }

Jacek

Posted in

Make a donation