Esempio n. 1
0
        public void ListenerCallback(IAsyncResult result)
        {
            try
            {
                System.Net.HttpListener        listener = (System.Net.HttpListener)result.AsyncState;
                System.Net.HttpListenerContext context  = listener.EndGetContext(result);

                System.Net.HttpListenerRequest  request  = context.Request;
                System.Net.HttpListenerResponse response = context.Response;

                _iprocessRequest.ProcessRequest(context);
            }
            catch (Exception ex)
            {
                ServerComms.LogError($"Http Listener falled {ex.Message}");
                _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener);
            }
        }
Esempio n. 2
0
        private bool TryConnectLocalIP()
        {
            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(ExternalUrl);
                try
                {
                    listener.Start();
                }
                catch (System.Net.HttpListenerException)
                {
                    return(false);
                }
                listener.Close();
            }

            return(true);
        }
Esempio n. 3
0
        internal static unsafe void SetRequestQueueLength(System.Net.HttpListener listener, long length)
        {
            Type         listenerType = typeof(System.Net.HttpListener);
            PropertyInfo requestQueueHandleProperty = listenerType.GetProperty("RequestQueueHandle", BindingFlags.NonPublic | BindingFlags.Instance);

            if (requestQueueHandleProperty == null || requestQueueHandleProperty.PropertyType != typeof(CriticalHandle))
            {
                // The property changed, no-op.
                return;
            }

            CriticalHandle requestQueueHandle = (CriticalHandle)requestQueueHandleProperty.GetValue(listener, null);
            uint           result             = HttpSetRequestQueueProperty(requestQueueHandle, HTTP_SERVER_PROPERTY.HttpServerQueueLengthProperty,
                                                                            new IntPtr((void *)&length), (uint)Marshal.SizeOf(length), 0, IntPtr.Zero);

            if (result != 0)
            {
                throw new Win32Exception((int)result);
            }
        }
Esempio n. 4
0
        private bool TryConnectLocalIP()
        {
            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(ExternalUrl);
                try
                {
                    listener.Start();
                }
                catch (System.Net.HttpListenerException e)
                {
                    e.ToString();
                    //System.Console.WriteLine(e);
                    return(false);
                }
                listener.Close();
            }

            return(true);
        }
Esempio n. 5
0
        public void WebServerCallback(IAsyncResult result)
        {
            Trace.TraceInformation("Enter.");

            try
            {
                System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;

                // Call EndGetContext to complete the asynchronous operation.
                System.Net.HttpListenerContext context = listener.EndGetContext(result);

                EnqueueRequest(context);
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception:" + ex.Message + Environment.NewLine + "StackTrace:" + ex.StackTrace);
            }

            Trace.TraceInformation("Current thread ID: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            //需要在程序根目录下建立bin目录,把程序拷一份让asp.net加载
            //aspx文件用的codefile模式,不是codebehind模式
            //aspx文件复制到程序运行目录
            var        path = System.Environment.CurrentDirectory;
            SimpleHost msh  = (SimpleHost)System.Web.Hosting.ApplicationHost.CreateApplicationHost(typeof(SimpleHost), "/", path);

            using (var ls = new System.Net.HttpListener())
            {
                ls.Prefixes.Add("http://localhost:8054/");
                ls.Start();
                while (true)
                {
                    var context = ls.GetContext();
                    context.Response.ContentType = "text/html; Charset=UTF-8";
                    context.Response.StatusCode  = 200;
                    System.Threading.ThreadPool.QueueUserWorkItem(x => msh.ProcessRequest(context.Request.Url, context.Response.OutputStream));
                }
            }
        }
Esempio n. 7
0
        public void CreateListener(Dictionary <String, X509Certificate2> prefixes)
        {
            var certProc = new CertificateProcessor(ServerComms);

            _listener = new System.Net.HttpListener();


            foreach (string s in prefixes.Keys)
            {
                certProc.AddCertificateToHost(s, prefixes[s]);
                _listener.Prefixes.Add(s);
            }
            _listener.Start();

            System.Threading.Tasks.Task.Factory.StartNew(() => {
                while (_listener.IsListening)
                {
                    var result = _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener);
                    result.AsyncWaitHandle.WaitOne();
                }
            });
        }
Esempio n. 8
0
        internal static unsafe void SetRequestQueueLength(System.Net.HttpListener listener, long length)
        {
            var requestQueueHandlePropertyInfo = typeof(System.Net.HttpListener).GetProperty("RequestQueueHandle", BindingFlags.NonPublic | BindingFlags.Instance);

            if (requestQueueHandlePropertyInfo == null || requestQueueHandlePropertyInfo.PropertyType != typeof(CriticalHandle))
            {
                throw new PlatformNotSupportedException();
            }

            var requestQueueHandle = (CriticalHandle)requestQueueHandlePropertyInfo.GetValue(listener, null);
            var result             = HttpSetRequestQueueProperty(
                requestQueueHandle,
                HTTP_SERVER_PROPERTY.HttpServerQueueLengthProperty,
                new IntPtr((void *)&length),
                (UInt32)Marshal.SizeOf(length),
                0,
                IntPtr.Zero
                );

            if (result != 0)
            {
                throw new Win32Exception((int)result);
            }
        }
Esempio n. 9
0
 public HttpServer(Server server)
 {
     _server   = server;
     _listener = new System.Net.HttpListener();
 }
Esempio n. 10
0
 public HttpListener(System.Net.HttpListener httpListener)
 {
     _httpListener = httpListener;
 }
Esempio n. 11
0
        public void Run()
        {
            if (!IsConnectedToInternet())
            {
                System.Console.WriteLine("Not connected to a network");
                return;
            }

            bool useLocalIP = true;

            if (!TryConnectLocalIP())
            {
                useLocalIP = false;
                System.Console.WriteLine("Could not connect through local IP address");
            }

            System.Console.WriteLine("Connect using {0}", baseUrl.TrimEnd('/'));
            if (useLocalIP)
            {
                System.Console.WriteLine("Connect using {0}", ExternalUrl.TrimEnd('/'));
            }

            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(baseUrl);
                if (useLocalIP)
                {
                    listener.Prefixes.Add(ExternalUrl);
                }

                listener.Start();
                while (true)
                {
                    System.Net.HttpListenerContext ctx     = listener.GetContext();
                    System.Net.HttpListenerRequest request = ctx.Request;
                    System.Console.WriteLine(request.Url);

                    System.Net.HttpListenerResponse response = ctx.Response;

                    string urlString = request.Url.ToString();
                    string rawUrl    = request.RawUrl.ToString();

                    string responseText = null;

                    byte[] reponseBuffer = null;
                    if (rawUrl == root)
                    {
                        responseText         = defaultPage;
                        responseText         = responseText.Replace(baseUrl, urlString + "/");
                        response.ContentType = "text/HTML";
                    }
                    else if (rawUrl.StartsWith(WebService.resourcePrefix))
                    {
                        string resourceName = rawUrl.Remove(0, WebService.resourcePrefix.Length);
                        if (rawUrl.EndsWith(".jpg"))
                        {
                            reponseBuffer        = Program.GetEmbeddedContentAsBinary(resourceName);
                            response.ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                        }
                        else
                        {
                            responseText         = Program.GetEmbeddedContent(resourceName);
                            response.ContentType = "text/css";
                        }
                    }
                    else if (rawUrl.StartsWith(root + "/"))
                    {
                        var streamReader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding);
                        var jsonRequest  = streamReader.ReadToEnd();

                        string requestedPage      = rawUrl.Remove(0, (root + "/").Length);
                        object unserializedObject = null;

                        Type serviceType;
                        if (mapNameToServiceType.TryGetValue(requestedPage, out serviceType))
                        {
                            unserializedObject = js.Deserialize(jsonRequest, serviceType);
                            if (unserializedObject == null)
                            {
                                unserializedObject = Activator.CreateInstance(serviceType);
                            }
                        }
                        else
                        {
                            System.Console.WriteLine("Unrecognized Service");
                        }

                        if (unserializedObject is IRequestWithHtmlResponse)
                        {
                            responseText = ((IRequestWithHtmlResponse)unserializedObject).GetResponse(this);
                        }
                        else if (unserializedObject is IRequestWithJsonResponse)
                        {
                            object o          = ((IRequestWithJsonResponse)unserializedObject).GetResponse(this);
                            var    serialized = js.Serialize(o);
                            responseText = serialized;
                        }
                        response.ContentType = "text/html";
                    }

                    if (response.ContentType != null && response.ContentType.StartsWith("text") && responseText != null)
                    {
                        response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                        reponseBuffer            = System.Text.Encoding.UTF8.GetBytes(responseText);
                    }

                    if (reponseBuffer != null)
                    {
                        //These headers to allow all browsers to get the response
                        response.Headers.Add("Access-Control-Allow-Credentials", "true");
                        response.Headers.Add("Access-Control-Allow-Origin", "*");
                        response.Headers.Add("Access-Control-Origin", "*");

                        //response.StatusCode = 200;
                        //response.StatusDescription = "OK";
                        // Get a response stream and write the response to it.
                        response.ContentLength64 = reponseBuffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(reponseBuffer, 0, reponseBuffer.Length);
                        output.Close();
                    }
                    response.Close();
                }
            }
        }
Esempio n. 12
0
        void Web()
        {
            System.Net.HttpListener listener = new System.Net.HttpListener();
            //Properties.Settings.Default.Host
            //listener.Prefixes.Add("http://localhost:8888/");
            listener.Prefixes.Add(Properties.Settings.Default.Host);
            listener.Start();
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        System.Net.HttpListenerContext context = listener.GetContext();
                        System.Net.HttpListenerRequest request = context.Request;
                        //DataStart = 2005-08-09T18: 31:42 & DataEnd = 2005-08-09T18: 31:42

                        var str = request.RawUrl.Split('&');
                        switch (str[0].ToUpper())
                        {
                        case "/WEIGHING":
                            WebWeighing(str, context);
                            break;

                        case "/CARS":
                            WebCars(str, request, context);
                            break;

                        case "/SHIPPERS":
                            WebShippers(str, request, context);
                            break;

                        case "/CONSIGNEE":
                            WebConsignee(str, request, context);
                            break;

                        case "/WEIGHMAN":
                            WebWeighman(str, request, context);
                            break;

                        case "/WEIGHINGMODE":
                            WebWeighingMode(str, context);
                            break;

                        case "/MATERIAL":
                            WebMaterial(str, request, context);
                            break;
                        }

                        /*
                         * MemoryStream stream1 = new MemoryStream();
                         * DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RecordWeight[]), new DataContractJsonSerializerSettings
                         * {
                         * DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
                         * });
                         * DateTime Start = DateTime.MinValue;
                         * DateTime End = DateTime.MaxValue;
                         * if (str[1].StartsWith("DateStart="))
                         * {
                         * var ts = str[1].Substring(10);
                         * Start = DateTime.Parse(ts);
                         * }
                         *
                         * if (str[2].StartsWith("DateEnd="))
                         * {
                         * var ts = str[2].Substring(8);
                         * End = DateTime.Parse(ts);
                         * }
                         * var rdr = new StreamReader(stream1, Encoding.UTF8);
                         * if (Start > End)
                         * continue;
                         * RecordWeight[] rec;
                         * lock (listWeight)
                         * {
                         * rec = listWeight.ToArray();
                         * }
                         * rec = rec.Where(x =>
                         * {
                         * var date = x.dataBrutto > x.dataTara ? x.dataBrutto : x.dataTara;
                         * return date >= Start && date <= End;
                         * }).ToArray();
                         * ser.WriteObject(stream1, rec);
                         * stream1.Position = 0;
                         * var ret = rdr.ReadToEnd();
                         * rdr.Close();
                         * stream1.Close();
                         * {
                         * {
                         *  System.Net.HttpListenerResponse response = context.Response;
                         *  response.ContentType = "application/json";
                         *
                         *  string responseString = ret;
                         *
                         *  byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                         *  response.ContentLength64 = buffer.Length;
                         *  Stream output = response.OutputStream;
                         *  output.Write(buffer, 0, buffer.Length);
                         *  output.Close();
                         * }
                         * }*/
                    } catch { }
                }
            });
        }
Esempio n. 13
0
        private void _Server()
        {
            Trace.TraceInformation("Enter.");

            System.Net.HttpListener _Listener = null;
            string sResponse = string.Empty;

            try
            {
                _Listener = new System.Net.HttpListener();
                _Listener.Prefixes.Add("http://" + _WebServerIP + ":" + _WebServerPort + "/" + _WebServerURIPrefix + "/");
                _Listener.Start();

                Trace.TraceInformation("Listener started for prefix " + "http://" + _WebServerIP + ":" + _WebServerPort + "/" + _WebServerURIPrefix + "/");

                if (Started != null)
                {
                    Started(this, new EventArgs());
                }

                do
                {
                    Trace.TraceInformation("Listening for request to be processed asyncronously.");

                    IAsyncResult result = _Listener.BeginGetContext(_Callback, _Listener);

                    Trace.TraceInformation("Waiting for request to be processed asyncronously.");

                    result.AsyncWaitHandle.WaitOne();

                    Trace.TraceInformation("Request processed asyncronously.");
                } while (true);
            }
            catch (System.Threading.ThreadAbortException abortEx)
            {
                Trace.TraceError("ThreadAbortException:" + abortEx.Message + Environment.NewLine + "StackTrace:" + abortEx.StackTrace);

                System.Threading.Thread.ResetAbort();

                _Abort.Set();

                if (Aborted != null)
                {
                    Aborted(this, new EventArgs());
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception:" + ex.Message + Environment.NewLine + "StackTrace:" + ex.StackTrace);

                _Abort.Set();

                if (Error != null)
                {
                    Error(this, new WebServerEventArgs("Exception:" + ex.Message + Environment.NewLine + "StackTrace:" + ex.StackTrace));
                }
            }
            finally
            {
                if (_Listener != null)
                {
                    if (_Listener.IsListening)
                    {
                        _Listener.Stop();
                    }
                }

                _Listener = null;
            }

            if (Stopped != null)
            {
                Stopped(this, new EventArgs());
            }
        }
Esempio n. 14
0
 public HttpListener()
 {
     mListener = new System.Net.HttpListener();
 }
Esempio n. 15
0
 public void StartWebServer()
 {
     HttpListener = new System.Net.HttpListener();
     HttpListener.Prefixes.Clear();
     HttpListener.Prefixes.Add(ListenerPrefix);
     KeepListening = true;
     ListenerThread = new System.Threading.Thread(new System.Threading.ThreadStart(WebServerListener));
     ListenerThread.IsBackground = true;
     ListenerThread.Start();
 }
Esempio n. 16
0
        public BlogServer(BlogServerOptions options)
        {
            if (options == null)
            {
                throw new System.ArgumentNullException("options");
            }
            this.Options = options;

            CreateFolderSafe(this.Options.OutputFolder);

            // Initialize the log
            string logfilename = GetLogFilename();
            Console.WriteLine("Log at: {0}", logfilename);
            if (this.Options.OverwriteLog)
            {
                LogStream = System.IO.File.CreateText(logfilename);                
            }
            else
            {
                LogStream = System.IO.File.AppendText(logfilename);                
            }
            LogStream.AutoFlush = true;

            this.WriteLog("----------------------------------------");
            this.WriteLog("Start New Server Session ");
            this.WriteLog("----------------------------------------");

            this.HostName = Environment.MachineName.ToLower();
            // The Primary url is what will normally be used
            // However the server supports using localhost as well
            this.ServerUrlPrimary = string.Format("http://{0}:{1}/", HostName, this.Options.Port);
            this.ServerUrlSecondary = string.Format("http://{0}:{1}/", "localhost", this.Options.Port);

            this.WriteLog("Primary Url: {0}", this.ServerUrlPrimary);
            this.WriteLog("Secondary Url: {0}", this.ServerUrlSecondary);
            // The title of the blog will be based on the class name
            this.BlogTitle = "Untitled Blog";

            // This server will contain a single user

            var adminuser = new BlogUser
            {
                Name = "admin",
                Password = "******"
            };

            // Setup Collections
            this.BlogList = new List<UserBlogInfo>();
            this.BlogUsers = new List<BlogUser>();
            this.PostList = new PostList();
            this.MediaObjectList = new MediaObjectList();
            this.CategoryList = new CategoryList();

            this.BlogUsers.Add(adminuser);
            
            // This server will contain a single blog
            this.BlogList.Add(new UserBlogInfo(adminuser.Name, this.ServerUrlPrimary, this.BlogTitle));

            // Add Placeholder Content
            if (this.Options.CreateSampleContent && this.PostList.Count < 1)
            {

                if (this.CategoryList.Count < 1)
                {
                    this.CategoryList.Add("0", "sports");
                    this.CategoryList.Add("0", "biology");
                    this.CategoryList.Add("0", "office supplies");
                    this.CategoryList.Add("0", "food");
                    this.CategoryList.Add("0", "tech");                    
                }

                var cats1 = new[] {"sports","biology", "office supplies"};
                var cats2 = new[] {"food"};
                var cats3 = new[] {"food" };
                var cats4 = new[] {"biology"};

                string lipsum =
                    "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

                this.PostList.Add(new System.DateTime(2012, 12, 2), "1000 Amazing Uses for Staples", lipsum, cats1, true);
                this.PostList.Add(new System.DateTime(2012, 1, 15), "Why Pizza is Great", lipsum, cats2, true);
                this.PostList.Add(new System.DateTime(2013, 4, 10), "Sandwiches I have loved", lipsum, cats3, true);
                this.PostList.Add(new System.DateTime(2013, 3, 31), "Useful Things You Can Do With a Giraffe", lipsum, cats4, true);
            }

            this.HttpListener = new System.Net.HttpListener();


        }
Esempio n. 17
0
        public void Run()
        {
            if (!IsConnectedToInternet())
            {
                System.Console.WriteLine("Not connected to a network");
                return;
            }

            bool useLocalIP = true;
            if (!TryConnectLocalIP())
            {
                useLocalIP = false;
                System.Console.WriteLine("Could not connect through local IP address");
            }

            System.Console.WriteLine("Connect using {0}", baseUrl.TrimEnd('/'));
            if (useLocalIP)
            {
                System.Console.WriteLine("Connect using {0}", ExternalUrl.TrimEnd('/'));
            }

            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(baseUrl);
                if (useLocalIP)
                {
                    listener.Prefixes.Add(ExternalUrl);
                }

                listener.Start();
                while (true)
                {
                    System.Net.HttpListenerContext ctx = listener.GetContext();
                    System.Net.HttpListenerRequest request = ctx.Request;
                    System.Console.WriteLine(request.Url);

                    System.Net.HttpListenerResponse response = ctx.Response;

                    string urlString = request.Url.ToString();
                    string rawUrl = request.RawUrl.ToString();

                    string responseText = null;

                    byte[] reponseBuffer = null;
                    if (rawUrl == root)
                    {
                        responseText = defaultPage;
                        responseText = responseText.Replace(baseUrl, urlString + "/");
                        response.ContentType = "text/HTML";
                    }
                    else if (rawUrl.StartsWith(WebService.resourcePrefix))
                    {
                        string resourceName = rawUrl.Remove(0, WebService.resourcePrefix.Length);
                        if (rawUrl.EndsWith(".jpg"))
                        {
                            reponseBuffer = Program.GetEmbeddedContentAsBinary(resourceName);
                            response.ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                        }
                        else
                        {
                            responseText = Program.GetEmbeddedContent(resourceName);
                            response.ContentType = "text/css";
                        }
                    }
                    else if (rawUrl.StartsWith(root + "/"))
                    {
                        var streamReader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding);
                        var jsonRequest = streamReader.ReadToEnd();

                        string requestedPage = rawUrl.Remove(0, (root + "/").Length);
                        object unserializedObject = null;

                        Type serviceType;
                        if (mapNameToServiceType.TryGetValue(requestedPage, out serviceType))
                        {
                            unserializedObject = js.Deserialize(jsonRequest, serviceType);
                            if (unserializedObject == null)
                            {
                                unserializedObject = Activator.CreateInstance(serviceType);
                            }
                        }
                        else
                        {
                            System.Console.WriteLine("Unrecognized Service");
                        }

                        if (unserializedObject is IRequestWithHtmlResponse)
                        {
                            responseText = ((IRequestWithHtmlResponse)unserializedObject).GetResponse(this);
                        }
                        else if (unserializedObject is IRequestWithJsonResponse)
                        {
                            object o = ((IRequestWithJsonResponse)unserializedObject).GetResponse(this);
                            var serialized = js.Serialize(o);
                            responseText = serialized;
                        }
                        response.ContentType = "text/html";
                    }

                    if (response.ContentType != null && response.ContentType.StartsWith("text") && responseText != null)
                    {
                        response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                        reponseBuffer = System.Text.Encoding.UTF8.GetBytes(responseText);
                    }

                    if (reponseBuffer != null)
                    {
                        //These headers to allow all browsers to get the response
                        response.Headers.Add("Access-Control-Allow-Credentials", "true");
                        response.Headers.Add("Access-Control-Allow-Origin", "*");
                        response.Headers.Add("Access-Control-Origin", "*");

                        //response.StatusCode = 200;
                        //response.StatusDescription = "OK";
                        // Get a response stream and write the response to it.
                        response.ContentLength64 = reponseBuffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(reponseBuffer, 0, reponseBuffer.Length);
                        output.Close();
                    }
                    response.Close();
                }
            }
        }
Esempio n. 18
0
        public BlogServer(BlogServerOptions options)
        {
            if (options == null)
            {
                throw new System.ArgumentNullException("options");
            }
            this.Options = options;

            CreateFolderSafe(this.Options.OutputFolder);

            // Initialize the log
            string logfilename = GetLogFilename();

            Console.WriteLine("Log at: {0}", logfilename);
            if (this.Options.OverwriteLog)
            {
                LogStream = System.IO.File.CreateText(logfilename);
            }
            else
            {
                LogStream = System.IO.File.AppendText(logfilename);
            }
            LogStream.AutoFlush = true;

            this.WriteLog("----------------------------------------");
            this.WriteLog("Start New Server Session ");
            this.WriteLog("----------------------------------------");

            this.HostName = Environment.MachineName.ToLower();
            // The Primary url is what will normally be used
            // However the server supports using localhost as well
            this.ServerUrlPrimary   = string.Format("http://{0}:{1}/", HostName, this.Options.Port);
            this.ServerUrlSecondary = string.Format("http://{0}:{1}/", "localhost", this.Options.Port);

            this.WriteLog("Primary Url: {0}", this.ServerUrlPrimary);
            this.WriteLog("Secondary Url: {0}", this.ServerUrlSecondary);
            // The title of the blog will be based on the class name
            this.BlogTitle = "Untitled Blog";

            // This server will contain a single user

            var adminuser = new BlogUser
            {
                Name     = "admin",
                Password = "******"
            };

            // Setup Collections
            this.BlogList        = new List <UserBlogInfo>();
            this.BlogUsers       = new List <BlogUser>();
            this.PostList        = new PostList();
            this.MediaObjectList = new MediaObjectList();
            this.CategoryList    = new CategoryList();

            this.BlogUsers.Add(adminuser);

            // This server will contain a single blog
            this.BlogList.Add(new UserBlogInfo(adminuser.Name, this.ServerUrlPrimary, this.BlogTitle));

            // Add Placeholder Content
            if (this.Options.CreateSampleContent && this.PostList.Count < 1)
            {
                if (this.CategoryList.Count < 1)
                {
                    this.CategoryList.Add("0", "sports");
                    this.CategoryList.Add("0", "biology");
                    this.CategoryList.Add("0", "office supplies");
                    this.CategoryList.Add("0", "food");
                    this.CategoryList.Add("0", "tech");
                }

                var cats1 = new[] { "sports", "biology", "office supplies" };
                var cats2 = new[] { "food" };
                var cats3 = new[] { "food" };
                var cats4 = new[] { "biology" };

                string lipsum =
                    "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

                this.PostList.Add(new System.DateTime(2012, 12, 2), "1000 Amazing Uses for Staples", lipsum, cats1, true);
                this.PostList.Add(new System.DateTime(2012, 1, 15), "Why Pizza is Great", lipsum, cats2, true);
                this.PostList.Add(new System.DateTime(2013, 4, 10), "Sandwiches I have loved", lipsum, cats3, true);
                this.PostList.Add(new System.DateTime(2013, 3, 31), "Useful Things You Can Do With a Giraffe", lipsum, cats4, true);
            }

            this.HttpListener = new System.Net.HttpListener();
        }
Esempio n. 19
0
 /// <summary>
 /// Dispose listener
 /// </summary>
 public void Dispose()
 {
     _listener = null;
 }
Esempio n. 20
0
 public SimpleServer(System.Net.HttpListener listener, string url, ProcessDataDelegate handler)
 {
     this.listener = listener;
     this.handler  = handler;
     listener.Prefixes.Add(url);
 }
Esempio n. 21
0
 public void StopWebServer()
 {
     try {
         KeepListening = false;
         HttpListener.Stop();
         HttpListener = null;
         ListenerThread = null;
     }
     catch { }
 }
Esempio n. 22
0
 public void MakeHttpPrefix(System.Net.HttpListener server)
 {
     server.Prefixes.Clear();
     server.Prefixes.Add("http://localhost:8082/");
     Logger.Info("LuaHttpServer添加监听前缀:http://localhost:8082/");
 }
Esempio n. 23
0
 public HttpListener(IBackgroundWorkerService backgroundWorkerService)
 {
     _backgroundWorkerService = backgroundWorkerService;
     _listener = new System.Net.HttpListener();
     _handlers = new List <HttpHandler>();
 }
Esempio n. 24
0
        static void Main(string[] args)
        {
            try
            {
                System.Net.HttpListener server = new System.Net.HttpListener();
                // Address, Port を指定
                server.Prefixes.Add("http://localhost:8000/");
                // サーバ起動
                server.Start();

                while (true)
                {
                    // 接続待ち
                    System.Net.HttpListenerContext context = server.GetContext();

                    // 応答作成
                    System.Net.HttpListenerResponse response = context.Response;
                    // JavaScriptエラー回避
                    response.Headers.Add("Access-Control-Allow-Origin", "*");

                    bool   readSuccess = false;
                    byte[] idm         = null;

                    if (System.Text.RegularExpressions.Regex.IsMatch(context.Request.Url.ToString(), "http://localhost:8000/getIDmDummy\\?seed=.*"))
                    {
                        // 疑似IDm生成
                        idm         = IDmDummy(context.Request.QueryString.Get("seed"));
                        readSuccess = true;

                        Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}]\t疑似IDm生成");
                    }
                    else
                    {
                        try
                        {
                            // NFC読み込み
                            Felica felica = new Felica();
                            felica.Polling((int)SystemCode.FelicaLiteS);
                            idm = felica.IDm();
                            felica.Dispose();

                            readSuccess = true;

                            Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}]\tカード読み取り成功");
                        }
                        catch
                        {
                            Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}]\tカード読み取り失敗");
                        }
                    }

                    if (readSuccess)
                    {
                        // 読み取り成功
                        string idm_str = BitConverter.ToString(idm).Replace("-", "").ToLower();
                        idm = Encoding.UTF8.GetBytes(idm_str);

                        response.StatusCode = 200;
                        response.OutputStream.Write(idm, 0, idm.Length);
                        response.Close();
                    }
                    else
                    {
                        // 読み取り失敗
                        response.StatusCode = 500;
                        response.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 25
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="listener"></param>
 public SystemHttpListener(System.Net.HttpListener listener)
 {
     _listener = listener;
     _prefixes = new();
 }
Esempio n. 26
0
 /// <summary>
 /// 服务开启前触发
 /// </summary>
 /// <param name="service"></param>
 /// <param name="httpListener"></param>
 private void ChatService_OnWebSocketServiceBeginStart(WebSocketService.Core.WebSocketService service, System.Net.HttpListener httpListener)
 {
     if (CreateRepositoryFunc == null)
     {
         httpListener.Close();
         throw new Exception("未设置资创建源库方法!");
     }
     using (var repository = CreateRepositoryFunc())
     {
         Users = repository.GetUsers().ToList();
     }
 }
Esempio n. 27
0
        private bool TryConnectLocalIP()
        {
            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(ExternalUrl);
                try
                {
                    listener.Start();
                }
                catch(System.Net.HttpListenerException e)
                {
                    e.ToString();
                    //System.Console.WriteLine(e);
                    return false;
                }
                listener.Close();
            }

            return true;
        }