BeginGetContext() public method

public BeginGetContext ( AsyncCallback callback, object state ) : IAsyncResult
callback AsyncCallback
state object
return IAsyncResult
コード例 #1
0
ファイル: PosHub.cs プロジェクト: alaidas/PlugNPay
        public void Start(string bindUrl)
        {
            Ensure.NotNull(bindUrl, nameof(bindUrl));

            _httpListener = new HttpListener { IgnoreWriteExceptions = false };
            _httpListener.Prefixes.Add(bindUrl);
            _httpListener.Start();


            AsyncCallback acceptConnection = null;
            acceptConnection = state =>
            {
                try
                {
                    HttpListenerContext clientContext = _httpListener.EndGetContext(state);
                    Log.Info($"New Ecr connection from: {clientContext.Request.RemoteEndPoint}");

                    ProcessAsync(clientContext);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
                finally
                {
                    _httpListener.BeginGetContext(acceptConnection, null);
                }
            };

            _httpListener.BeginGetContext(acceptConnection, null);

            RegisterActions();
        }
コード例 #2
0
ファイル: TestWebSeed.cs プロジェクト: Cyarix/monotorrent
        public void Setup()
        {
            requestedUrl.Clear();
            partialData = false;
            int i;
            for (i = 0; i < 1000; i++)
            {
                try
                {
                    listener = new HttpListener();
                    listener.Prefixes.Add(string.Format(listenerURL, i));
                    listener.Start();
                    break;
                }
                catch
                {

                }
            }
            listener.BeginGetContext(GotContext, null);
            rig = TestRig.CreateMultiFile();
            connection = new HttpConnection(new Uri(string.Format(listenerURL, i)));
            connection.Manager = rig.Manager;

            id = new PeerId(new Peer("this is my id", connection.Uri), rig.Manager);
            id.Connection = connection;
            id.IsChoking = false;
            id.AmInterested = true;
            id.BitField.SetAll(true);
            id.MaxPendingRequests = numberOfPieces;
            
            requests = rig.Manager.PieceManager.Picker.PickPiece(id, new List<PeerId>(), numberOfPieces);
        }
コード例 #3
0
ファイル: HttpListener.cs プロジェクト: ruo2012/Framework-1
 /// <summary>
 /// Http监听器
 /// </summary>
 /// <param name="host">监听host</param>
 /// <param name="port">监听端口</param>
 public HttpListener(string host = "*", int port = 9478)
 {
     listener = new Listener();
     listener.Prefixes.Add("http://" + host + ":" + port + "/");
     listener.Start();
     listener.BeginGetContext(ListenedRequest, null);
 }
コード例 #4
0
        private static void Main(string[] args)
        {
            XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net_server.config"));

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            Thread.CurrentThread.Name = "Entry";

            Database = new Database();
            GameData = new XmlData();

            InstanceId = Guid.NewGuid().ToString();
            Console.CancelKeyPress += (sender, e) => e.Cancel = true;

            if (RunPreCheck(port))
            {
                listener = new HttpListener();
                listener.Prefixes.Add($"http://*:{port}/");
                listener.Start();
                listener.BeginGetContext(ListenerCallback, null);
                Logger.Info($"Listening at port {port}...");
            }
            else
                Logger.Error($"Port {port} is occupied");

            while (Console.ReadKey(true).Key != ConsoleKey.Escape) ;

            Logger.Info("Terminating...");
            while (currentRequests.Count > 0) ;
            listener?.Stop();
        }
コード例 #5
0
ファイル: HttpServer.cs プロジェクト: jschell/JabbR.Eto
        public HttpServer(string baseDirectory)
        {
            this.baseDirectory = baseDirectory;
            var rnd = new Random();

            for (int i = 0; i < 100; i++)
            {
                int port = rnd.Next(49152, 65536);

                try
                {
                    listener = new HttpListener();
                    listener.Prefixes.Add("http://localhost:" + port + "/");
                    listener.Start();

                    this.port = port;
                    listener.BeginGetContext(ListenerCallback, null);
                    return;
                }
                catch (Exception x)
                {
                    listener.Close();
                    Debug.WriteLine("HttpListener.Start:\n" + x);
                }
            }

            throw new ApplicationException("Failed to start HttpListener");
        }
コード例 #6
0
        public DetergentHttpListener(
            string uriPrefix,
            string applicationPath,
            IDetergentHttpHandler detergentHttpHandler)
        {
            if (uriPrefix == null)
                throw new ArgumentNullException("uriPrefix");
            if (applicationPath == null)
                throw new ArgumentNullException("applicationPath");
            if (detergentHttpHandler == null) throw new ArgumentNullException("detergentHttpHandler");

            this.uriPrefix = uriPrefix;
            this.applicationPath = applicationPath;
            this.detergentHttpHandler = detergentHttpHandler;
            httpListener = new HttpListener();

            applicationRootUrl = new Uri(new Uri(uriPrefix), applicationPath).ToString();
            if (false == applicationRootUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase))
                applicationRootUrl = applicationRootUrl + '/';

            httpListener.Prefixes.Add(applicationRootUrl);

            DumpDiagnostics();

            httpListener.Start();
            IAsyncResult result = httpListener.BeginGetContext(WebRequestCallback, httpListener);
        }
コード例 #7
0
ファイル: ServerModel.cs プロジェクト: RedRecondite/TicTacToe
 public ServerModel()
 {
     mListener = new HttpListener();
     mListener.Prefixes.Add( "http://*:8181/" );
     mListener.Start();
     mListener.BeginGetContext( new AsyncCallback( ListenerCallback ), mListener );
 }
コード例 #8
0
        public static void GetContext(System.Net.HttpListener listener, Action <Exception, System.Net.HttpListenerContext> callback)
        {
            try
            {
                listener.BeginGetContext((result) =>
                {
                    try
                    {
                        var context = listener.EndGetContext(result);

                        Loop.Post(() =>
                        {
                            callback(null, context);
                        });
                    }
                    catch (Exception exception)
                    {
                        Loop.Post(() =>
                        {
                            callback(exception, null);
                        });
                    }
                }, null);
            }
            catch (Exception exception)
            {
                callback(exception, null);
            }
        }
コード例 #9
0
ファイル: MicroHttpServer.cs プロジェクト: semirs/CellAO
 public void Start()
 {
     httpListener = new HttpListener();
     httpListener.Prefixes.Add("http://localhost:" + this.ListenPort + "/");
     httpListener.Start();
     httpListener.BeginGetContext(this.OnNewRequest, null);
 }
コード例 #10
0
ファイル: Main.cs プロジェクト: eugenkrizo/tablet-clipboard
		static HttpListener listener; // http server providing clipboard history selection

		public static void Main (string[] args)
		{
			// make UI methods for clipboard access available
			Application.Init ();

			// setup http interface
			listener = new HttpListener();
			listener.Prefixes.Add("http://*:5544/");
			listener.Start();
			listener.BeginGetContext(ProcessRequest, null);

			// initialize access to clipboard
			clippy = Gtk.Clipboard.Get(Gdk.Atom.Intern("PRIMARY", false));

			// schedule polling of clipboard content
			timer = new System.Timers.Timer(300);
			timer.Elapsed += new System.Timers.ElapsedEventHandler(ReadClipboardUI);
			timer.Start();

			// just to prevent termination of the app
			Application.Run();

			// shutdown http interface
			listener.Stop();
		}
コード例 #11
0
        // Loop here to begin processing of new requests.
        protected virtual void Listen(object state)
        {
            while (IsListening)
            {
                if (Listener == null)
                {
                    return;
                }

                try
                {
                    Listener.BeginGetContext(ListenerCallback, Listener);
                    ListenForNextRequest.WaitOne();
                }
                catch (Exception ex)
                {
                    Log.Error("Listen()", ex);
                    return;
                }
                if (Listener == null)
                {
                    return;
                }
            }
        }
コード例 #12
0
        private void EndGetRequest(IAsyncResult result)
        {
            HttpListenerContext context = null;

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

            try
            {
                context = listener.EndGetContext(result);
                using (context.Response)
                    HandleRequest(context);
            }
            catch (Exception ex)
            {
                Console.Write("Exception in listener: {0}{1}", Environment.NewLine, ex);
            }
            finally
            {
                try
                {
                    if (listener.IsListening)
                    {
                        listener.BeginGetContext(EndGetRequest, listener);
                    }
                }
                catch
                {
                    Stop();
                }
            }
        }
コード例 #13
0
ファイル: HttpServer.cs プロジェクト: nathanpalmer/ravendb
		public void Start()
		{
			listener = new HttpListener();
			string virtualDirectory = Configuration.VirtualDirectory;
			if (virtualDirectory.EndsWith("/") == false)
				virtualDirectory = virtualDirectory + "/";
			listener.Prefixes.Add("http://+:" + Configuration.Port + virtualDirectory);
			switch (Configuration.AnonymousUserAccessMode)
			{
				case AnonymousUserAccessMode.None:
					listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
					break;
                case AnonymousUserAccessMode.All:
			        break;
				case AnonymousUserAccessMode.Get:
					listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication |
						AuthenticationSchemes.Anonymous;
			        listener.AuthenticationSchemeSelectorDelegate = request =>
			        {
                        return request.HttpMethod == "GET" || request.HttpMethod == "HEAD" ? 
                            AuthenticationSchemes.Anonymous : 
                            AuthenticationSchemes.IntegratedWindowsAuthentication;
			        };
					break;
                default:
			        throw new ArgumentException("Cannot understand access mode: " + Configuration.AnonymousUserAccessMode   );
			}

			listener.Start();
			listener.BeginGetContext(GetContext, null);
		}
コード例 #14
0
ファイル: Sewers.cs プロジェクト: pldcanfly/demonhunter
        public Sewers()
        {
            _listener = new HttpListener();
            string prefix = "http://*:81/";
            _listener.Prefixes.Add(prefix);
            _messages = new Demonic("127.0.0.1");
            _messages.setName("Black Temple");
            _messages.setPort(11201);
            _messages.addMethod("RESPONSE");
            _messages.setCallback(onMessageRecieved);
            _messages.init();

            try
            {
                _listener.Start();
                while (true)
                {
                    System.Console.WriteLine("Listening");
                    IAsyncResult result = _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener);
                    result.AsyncWaitHandle.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
            }
        }
コード例 #15
0
 public AsyncHttpServer()
 {
     _listener = new HttpListener();
     _listener.Prefixes.Add("http://+:80/");
     _listener.Start();
     _listener.BeginGetContext(GetContext, null);
 }
コード例 #16
0
        void processData(IAsyncResult result)
        {
            //System.Windows.Forms.MessageBox.Show("in process data");
            string               reqString;
            HttpListener         thisListener = (HttpListener)result.AsyncState;
            HttpListenerContext  thisContext  = thisListener.EndGetContext(result);
            HttpListenerRequest  thisRequest  = thisContext.Request;
            HttpListenerResponse thisResponse = thisContext.Response;

            try
            {
                System.IO.Stream       body     = thisRequest.InputStream;
                System.Text.Encoding   encoding = thisRequest.ContentEncoding;
                System.IO.StreamReader reader   = new System.IO.StreamReader(body, encoding);
                reqString = reader.ReadToEnd();
                byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes(raiseNewRequest(reqString));

                thisContext.Response.ContentLength64 = outBuffer.Length;
                thisContext.Response.OutputStream.Write(outBuffer, 0, outBuffer.Length);
                thisContext.Response.OutputStream.Close();
                System.IAsyncResult listenerResult = hListener.BeginGetContext(new AsyncCallback(processData), hListener);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Error reading http request: " + e.Message);
            }
        }
コード例 #17
0
 public HttpServer()
 {
     this.listener = new HttpListener();
     listener.Prefixes.Add(URL + "/");
     listener.Start();
     listener.BeginGetContext(new AsyncCallback(ListenerCallback), null);
 }
コード例 #18
0
        /// <summary>
        /// Starts the Authorisation listener to listen to the specified port.
        /// </summary>
        /// <param name="port"></param>
        public void ListenTo(int port)
        {
            if (!HttpListener.IsSupported)
            {
                Debug.Write("AuthListener unsupported: Windows XP SP2 or Server 2003 is required");
                throw new NotSupportedException("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
            }

            try
            {
                this._server = new HttpListener();

                var prefix = String.Format("http://localhost:{0}/", port);
                this._server.Prefixes.Add(prefix);
                Debug.WriteLine("Prefix " + prefix + " added.");

                // Start listening for client requests.
                this._server.Start();
                Debug.WriteLine("Waiting for a connection... ");

                // Start waiting for a request
                _server.BeginGetContext(new AsyncCallback(ListenerCallback), _server);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
                this.Stop();
            }
        }
コード例 #19
0
        protected void Run()
        {
            _listener = new HttpListener();
            _listener.Prefixes.Add(Host);
            _listener.Start();

            _listener.BeginGetContext(GetContext, null);
        }
コード例 #20
0
ファイル: StateListener.cs プロジェクト: cnalwaysroad/Urge
 /// <summary>
 /// 启动监听
 /// </summary>
 public static void Start(int port)
 {
     listener = new HttpListener();
     listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
     listener.Prefixes.Add(string.Format("http://*:{0}/", port));
     listener.Start();
     listener.BeginGetContext(new System.AsyncCallback(GetContextCallBack), listener);
 }
コード例 #21
0
		public HttpLogServer() {
			Handlers = CreateDefaultHandlers( );
			Listener = new HttpListener()
				{ Prefixes = { Program.PrimaryPrefix }
				};
			Listener.Start();
			Listener.BeginGetContext(OnGetContext,null);
		}
コード例 #22
0
ファイル: HttpWebServer.cs プロジェクト: happyt/webServer
 //===================================================================
 /// <summary>
 /// Creates the http server and opens listener
 /// </summary>
 public void Start()
 {
     listener = new HttpListener();
     listener.Prefixes.Add("http://*:" + portNumber + "/");
     listener.Start();
     listener.BeginGetContext(ProcessRequest, listener);
     Console.WriteLine("Connection Started");
 }
コード例 #23
0
ファイル: Server.cs プロジェクト: jorik041/rt
 public void Run()
 {
     listener = new HttpListener ();
     var p = "http://+:" + port + "/";
     listener.Prefixes.Add (p);
     listener.Start ();
     System.Console.WriteLine ("Serving {0}...", p);
     listener.BeginGetContext (OnContext, null);
 }
コード例 #24
0
        public void Start()
        {
            m_listener = new HttpListener();
            m_listener.Prefixes.Add(String.Format("http://*****:*****@"WopiServer Started");
        }
コード例 #25
0
ファイル: HttpServer.cs プロジェクト: jorik041/Knossus
 public void Start()
 {
     _listener = new HttpListener ();
     var prefix = "http://localhost:8081/";
     Debug.WriteLine (prefix);
     _listener.Prefixes.Add (prefix);
     _listener.Start ();
     _listener.BeginGetContext (HandleContext, null);
 }
コード例 #26
0
ファイル: WopiServer.cs プロジェクト: plutext/WopiBasicEditor
        public void Start()
        {
            _listener = new HttpListener();
            _listener.Prefixes.Add(@"http://+:" + _port + @"/");
            _listener.Start();
            _listener.BeginGetContext(ProcessRequest, _listener);

            Console.WriteLine(@"WopiServer Started");
        }
コード例 #27
0
        public HttpCallback()
        {
            _wait = new AutoResetEvent(false);

            _listener = new HttpListener();
            _listener.Prefixes.Add(CallbackUri);
            _listener.Start();
            _listener.BeginGetContext(OnCallback, null);
        }
コード例 #28
0
ファイル: DataportServer.cs プロジェクト: Mystika/fileport
 public void Start()
 {
     listener = new HttpListener();
     listener.Prefixes.Clear();
     listener.Prefixes.Add(String.Format("http://+:{0}/", _Port));
     listener.Start();
     listener.BeginGetContext(GetCallback, null);
     _IsRunning = true;
 }
コード例 #29
0
        /// <summary>
        ///     Starts listening for incoming connections
        /// </summary>
        public override void Start()
        {
            if (Running)
                return;

            listener = new System.Net.HttpListener();
            listener.Prefixes.Add(prefix);
            listener.Start();
            listener.BeginGetContext(EndGetRequest, listener);
        }
コード例 #30
0
ファイル: SimpleHttpServer.cs プロジェクト: slodge/ProtoPad
        public SimpleHttpServer(ResponseBytesWithResultHandler responseBytesWithResultHandler)
        {
            _responseBytesWithResultHandler = responseBytesWithResultHandler;
            _listener = new HttpListener();
            _listener.Prefixes.Add("http://*:8080/");
            _listener.Start();
            _listener.BeginGetContext(HandleRequest, _listener);

            Debug.WriteLine("Server started");
        }
コード例 #31
0
ファイル: ChatClientHost.cs プロジェクト: LittlePeng/ncuhome
        static void StartHttpListener(int port)
        {

            //启动http监听
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add(string.Format("http://+:{0}/", port.ToString()));
            listener.Start();

            listener.BeginGetContext(EndGetContext, listener);
        }
コード例 #32
0
ファイル: MetadataResolverTest.cs プロジェクト: nlhepler/mono
		public void StartupServer ()
		{
			if (listener != null)
				listener.Stop ();
			listener = new HttpListener ();
			listener.Prefixes.Add ("http://*:37564/echo/");
			listener.Start ();
			current_request = listener.BeginGetContext (OnReceivedRequest, null);
			remaining = 1;
		}
コード例 #33
0
ファイル: SimpleHttpServer.cs プロジェクト: tluyben/ProtoPad
        public SimpleHttpServer(int port, Dictionary<string, Func<byte[], string>> requestHandlers)
        {
            _requestHandlers = requestHandlers;
            _listener = new HttpListener();
            _listener.Prefixes.Add(String.Format("http://*:{0}/", port));
            _listener.Start();
            _listener.BeginGetContext(HandleRequest, _listener);

            Debug.WriteLine("ProtoPad HTTP Server started");
        }
コード例 #34
0
        public void Start(string uriPrefix, Action <HttpListenerContext> sessionReceived)
        {
            _httpServer = new System.Net.HttpListener();
            _httpServer.Prefixes.Add(uriPrefix);
            _httpServer.Start();

            _running = true;

            _httpServer.BeginGetContext(HandleRequest, new SessionState(this, sessionReceived));
        }
コード例 #35
0
 public WebLogTarget()
 {
     port = defaultPort;
     listener = new HttpListener();
     listener.Prefixes.Add("http://127.0.0.1:" + port + "/page/");
     listener.Prefixes.Add("http://127.0.0.1:" + port + "/update/");
     listener.Start();
     listener.BeginGetContext(processRequest, null);
     prepareLogPage();
 }
コード例 #36
0
ファイル: Form1.cs プロジェクト: esetomo/ScreenToHTTP
        public Form1()
        {
            InitializeComponent();

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:10158/");
            listener.Start();

            listener.BeginGetContext(OnGetContext, listener);
        }
コード例 #37
0
ファイル: HttpServerBase.cs プロジェクト: uzbekdev1/tscamera
 public virtual void Start()
 {
     try
     {
         _listener = new System.Net.HttpListener();
         _listener.Prefixes.Add(string.Format("http://+:{0}/{1}", Port, Prefix));
         _listener.Start();
         _listener.BeginGetContext(this.Listener_Request, _listener);
     }
     catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
 }
コード例 #38
0
        /// <summary>
        /// Starts listening for incoming connections
        /// </summary>
        public override void Start()
        {
            if (Running)
            {
                return;
            }

            listener = new System.Net.HttpListener();
            listener.Prefixes.Add(prefix);
            listener.Start();
            listener.BeginGetContext(EndGetRequest, listener);
        }
コード例 #39
0
        private void WebRequestCallback(IAsyncResult result)
        {
            if (Listener == null)
            {
                return;
            }

            HttpListenerContext Context = this.Listener.EndGetContext(result);

            Listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.Listener);

            ProcessRequest(Context);
        }
コード例 #40
0
        /// <summary>
        /// 监听到请求时
        /// </summary>
        private void ListenedRequest(IAsyncResult result)
        {
            var context = listener.EndGetContext(result);

            if (OnRequest != null)
            {
                try
                {
                    OnRequest.Invoke(context);
                }
                catch { }
            }
            listener.BeginGetContext(ListenedRequest, null);
        }
コード例 #41
0
        private void connected(IAsyncResult result)
        {
            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;
            HttpListenerContext     context  = null;

            try
            {
                context = listener.EndGetContext(result);
            }
            catch (Exception)
            {
                return;
            }



            requestedPath        = context.Request.Url.AbsolutePath;
            reqeustedContentType = context.Request.ContentType;

            using (StreamReader reader = new StreamReader(context.Request.InputStream))
            {
                postData = reader.ReadToEnd();
            }

            lock (this.resWriters)
            {
                if (resIdx < this.resWriters.Count)
                {
                    resWriters[resIdx].writeResponse(context.Response);
                }
                else
                {
                    resWriters[resWriters.Count - 1].writeResponse(context.Response);
                }

                resIdx++;
            }

            context.Response.OutputStream.Close();

            try
            {
                listener.BeginGetContext(this.connected, listener);
            }
            catch (Exception)
            {
                return;
            }
        }
コード例 #42
0
 public void Start()
 {
     if (IsRunning)
     {
         return;
     }
     listener = new HttpListener();
     //prefixes.Add("http://127.0.0.1:8000/");
     //prefixes.Add("http://192.168.7.245:8000/");
     foreach (string prefix in prefixes)
     {
         listener.Prefixes.Add(prefix);
     }
     listener.Start();
     listener.BeginGetContext(EndGetRequest, listener);
 }
コード例 #43
0
        static void httpListenerCallback(IAsyncResult result)
        {
            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;
            try
            {
                if (listener.IsListening)
                {
                    // continue to listen
                    listener.BeginGetContext(new AsyncCallback(httpListenerCallback), listener);

                    // handle the incoming request
                    System.Net.HttpListenerContext context = listener.EndGetContext(result);
                    System.Net.HttpListenerRequest request = context.Request;
                    string responseString;
                    if (string.Compare("/appletv/us/js/application.js", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\application.js");
                    }
                    else if (string.Compare("/appletv/us/nav.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\index.xml");
                    }
                    else if (string.Compare("/appletv/studios/marvel/ironman3/index-hd.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.index-hd.xml");
                    }
                    else if (string.Compare("/appletv/studios/marvel/ironman3/videos/trailer1-hd.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.videos.trailer1-hd.xml");
                    }
                    else
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml");
                    }
                    System.Net.HttpListenerResponse response = context.Response;
                    //string responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml");
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #44
0
        private void ContextResult(IAsyncResult ar)
        {
            System.Net.HttpListener listener = ar.AsyncState as System.Net.HttpListener;
            listener.BeginGetContext(ContextResult, listener);
            HttpListenerContext context = null;

            try
            {
                context = listener.EndGetContext(ar);
            }
            catch
            {
            }
            if (context != null)
            {
                OnRequest(new HttpRequest(context));
            }
        }
コード例 #45
0
        public virtual void Start()
        {
            try
            {
                Debug.Assert(string.IsNullOrEmpty(Prefix) || Prefix.EndsWith("/"));

                _listener = new HttpListener();
                _listener.IgnoreWriteExceptions = true;
#if DEBUG
                _listener.Prefixes.Add(string.Format("http://localhost:{0}/{1}", Port, Prefix));
#else
                _listener.Prefixes.Add(string.Format("http://+:{0}/{1}", Port, Prefix));
#endif

                _listener.Start();
                _listener.BeginGetContext(this.Listener_Request, _listener);
            }
            catch (Exception ex) { TraceLog.WriteException(ex); throw; }
        }
コード例 #46
0
 public bool start()
 {
     if (!System.Net.HttpListener.IsSupported)
     {
         System.Windows.Forms.MessageBox.Show("Windows XP SP2 or later required");
         return(false);
     }
     hListener = new System.Net.HttpListener();
     hListener.Prefixes.Add("http://+:" + listenPort + "/");
     try
     {
         hListener.Start();
         System.IAsyncResult listenerResult = hListener.BeginGetContext(new AsyncCallback(processData), hListener);
         return(true);
     }
     catch (Exception e)
     {
         System.Windows.Forms.MessageBox.Show("Could not start httpListener. Details: " + e.Message);
         return(false);
     }
 }
コード例 #47
0
        private static void HandleRequest(IAsyncResult result)
        {
            SessionState state = (SessionState)result.AsyncState;

            System.Net.HttpListener server = state.Server._httpServer;

            try
            {
                HttpListenerContext context = server.EndGetContext(result);
                server.BeginGetContext(HandleRequest, state);

                Task task = new Task(() => HandleSession(context, state), TaskCreationOptions.LongRunning);
                task.Start();
            }
            catch (Exception)
            {
                if (state.Server.IsRunning)
                {
                    throw;
                }
            }
        }
コード例 #48
0
        private void EndGetRequest(IAsyncResult result)
        {
            HttpListenerContext context = null;

            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;
            try
            {
                context = listener.EndGetContext(result);
                HandleRequest(context);
            }
            catch { }
            finally
            {
                if (context != null)
                {
                    context.Response.Close();
                }
                if (listener.IsListening)
                {
                    listener.BeginGetContext(EndGetRequest, listener);
                }
            }
        }
コード例 #49
0
        static void Main1(string[] args)
        {
            System.Configuration.Install.InstallContext _args = new System.Configuration.Install.InstallContext(null, args);
            if (_args.IsParameterTrue("debug"))
            {
                System.Console.WriteLine("Wait for debugger, press any key to continue...");
                System.Console.ReadKey();
            }

            System.Net.HttpListener listener = new System.Net.HttpListener();
            listener.Prefixes.Add("http://+:80/");
            listener.Start();
            listener.BeginGetContext(new AsyncCallback(httpListenerCallback), listener);
            bool quit = false;

            System.Console.WriteLine("Http starts, press x to terminate...");
            while (!quit)
            {
                if (System.Console.KeyAvailable)
                {
                    System.ConsoleKeyInfo k = System.Console.ReadKey();
                    if (k.KeyChar == 'x')
                    {
                        quit = true;
                    }
                }
                if (!quit)
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
            if (listener.IsListening)
            {
                listener.Stop();
            }
            listener.Close();
        }
コード例 #50
0
 public void RegisterRequestHandler(Action <Request, IResponseBuffer> requestHandler)
 {
     _httpListener.BeginGetContext(TryToPassRequestToHandler(requestHandler), _httpListener);
 }
コード例 #51
0
 /// <summary>
 /// 启动服务器
 /// </summary>
 /// <param name="uriPrefix"></param>
 public void Start(string uriPrefix = "http://+:8089/")
 {
     listener.Prefixes.Add(uriPrefix);
     listener.Start();
     listener.BeginGetContext(ContextResult, listener);
 }
コード例 #52
0
        private void OnAuthButtonClicked(object sender, EventArgs args)
        {
            if (listener != null && listener.IsListening)
            {
                listener.Stop();
                listener.Close();
            }

            // TODO: Move this
            if (Auth == null)
            {
                Auth = new Api.OAuth();
            }

            string rootUri = Server + "/api/1.0";

            try {
                RootInfo root = RootInfo.GetRoot(rootUri, new Api.AnonymousConnection());

                Auth.AuthorizeLocation   = root.AuthorizeUrl;
                Auth.AccessTokenBaseUrl  = root.AccessTokenUrl;
                Auth.RequestTokenBaseUrl = root.RequestTokenUrl;
                Auth.ConsumerKey         = "anyone";
                Auth.ConsumerSecret      = "anyone";
                Auth.Realm = "Snowy";
            } catch (Exception e) {
                Logger.Error("Failed to get Root resource " + rootUri + ". Exception was: " + e.ToString());
                authButton.Label = Catalog.GetString("Server not responding. Try again later.");
                oauth            = null;
                return;
            }

            if (!Auth.IsAccessToken)
            {
                listener = new HL.HttpListener();
                int    portToTry   = 8000;
                string callbackUrl = string.Empty;
                while (!listener.IsListening && portToTry < 9000)
                {
                    callbackUrl = String.Format("http://localhost:{0}/tomboy-web-sync/",
                                                portToTry);
                    try {
                        listener.Prefixes.Add(callbackUrl);
                    } catch (Exception e) {
                        Logger.Error("Exception while trying to add {0} as an HttpListener Prefix",
                                     callbackUrl);
                        Logger.Error(e.ToString());
                        break;
                    }
                    try {
                        listener.Start();
                        Auth.CallbackUrl = callbackUrl;
                    } catch {
                        listener.Prefixes.Clear();
                        portToTry++;
                    }
                }

                if (!listener.IsListening)
                {
                    Logger.Error("Unable to start HttpListener on any port between 8000-8999");
                    authButton.Label = Catalog.GetString("Server not responding. Try again later.");
                    oauth            = null;
                    return;
                }

                Logger.Debug("Listening on {0} for OAuth callback", callbackUrl);
                string authUrl = string.Empty;
                try {
                    authUrl = Auth.GetAuthorizationUrl();
                } catch (Exception e) {
                    listener.Stop();
                    listener.Close();
                    Logger.Error("Failed to get auth URL from " + Server + ". Exception was: " + e.ToString());
                    // Translators: The web service supporting Tomboy WebSync is not responding as expected
                    authButton.Label = Catalog.GetString("Server not responding. Try again later.");
                    oauth            = null;
                    return;
                }

                IAsyncResult result = listener.BeginGetContext(delegate(IAsyncResult localResult) {
                    HL.HttpListenerContext context;
                    try {
                        context = listener.EndGetContext(localResult);
                    } catch (Exception e) {
                        // TODO: Figure out why this error occurs
                        Logger.Error("Error processing OAuth callback. Could be a sign that you pressed the button to reset the connection. Exception details:");
                        Logger.Error(e.ToString());
                        return;
                    }
                    // Assuming if we got here user clicked Allow
                    Logger.Debug("Context request uri query section: " + context.Request.Url.Query);
                    // oauth_verifier is required in OAuth 1.0a, not 1.0
                    var qs = HttpUtility.ParseQueryString(context.Request.Url.Query);
                    if (!String.IsNullOrEmpty(qs ["oauth_verifier"]))
                    {
                        Auth.Verifier = qs ["oauth_verifier"];
                    }
                    try {
                        if (!Auth.GetAccessAfterAuthorization())
                        {
                            throw new ApplicationException("Unknown error getting access token");
                        }
                        Logger.Debug("Successfully authorized web sync");
                    } catch (Exception e) {
                        listener.Stop();
                        listener.Close();
                        Logger.Error("Failed to authorize web sync, with exception:");
                        Logger.Error(e.ToString());
                        Gtk.Application.Invoke(delegate {
                            authButton.Label     = Catalog.GetString("Authorization Failed, Try Again");
                            authButton.Sensitive = true;
                        });
                        oauth = null;
                        return;
                    }
                    string htmlResponse =
                        String.Format(callbackHtmlTemplate,
                                      // Translators: Title of web page presented to user after they authorized Tomboy for sync
                                      Catalog.GetString("Tomboy Web Authorization Successful"),
                                      // Translators: Body of web page presented to user after they authorized Tomboy for sync
                                      Catalog.GetString("Please return to the Tomboy Preferences window and press Save to start synchronizing."));
                    using (var writer = new System.IO.StreamWriter(context.Response.OutputStream))
                        writer.Write(htmlResponse);
                    listener.Stop();
                    listener.Close();

                    if (Auth.IsAccessToken)
                    {
                        Gtk.Application.Invoke(delegate {
                            authButton.Sensitive = false;
                            authButton.Label     = Catalog.GetString("Connected. Press Save to start synchronizing");
                        });
                    }
                }, null);

                Logger.Debug("Launching browser to authorize web sync: " + authUrl);
                authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)");
                try {
                    Services.NativeApplication.OpenUrl(authUrl, Screen);
                } catch (Exception e) {
                    listener.Stop();
                    listener.Close();
                    Logger.Error("Exception opening URL: " + e.Message);
                    // Translators: Sometimes a user's default browser is not set, so we recommend setting it and trying again
                    authButton.Label = Catalog.GetString("Set the default browser and try again");
                    return;
                }
                // Translators: The user must take action in their web browser to continue the authorization process
                authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)");
            }
        }
コード例 #53
0
 void QueueNextRequestPending()
 {
     _listener.BeginGetContext(ProcessRequest, null);
 }
コード例 #54
0
 public void BeginGetContext(AsyncCallback callback, object state)
 {
     _listener.BeginGetContext(callback, state);
 }
コード例 #55
0
ファイル: IHttpListener.cs プロジェクト: 07artem132/Grapevine
 public IAsyncResult BeginGetContext(AsyncCallback callback, object state)
 {
     return(InnerListener.BeginGetContext(callback, state));
 }