public async Task StartAsync() { try { HttpListener.Start(); isFinished = new ManualResetEvent(false); logger?.LogInformation("HttpListener for requests on [{0}] running!", string.Join(", ", UriPrefixes)); while (!isFinished.WaitOne(0) && HttpListener.IsListening) { var ctx = await HttpListener.GetContextAsync(); Request request = new Request(ctx); Response response = new Response(ctx); // logger?.LogDebug("{0}: {1} {2}", DateTime.Now, request.Method, request.Endpoint); Console.WriteLine("HttpListener {0}: {1} {2}", DateTime.Now, request.Method, request.Endpoint); OnRequest?.Invoke(request, response); } } catch (Exception e) { logger?.LogError("HttpListener StartAsync Error:{0}", e.Message); } finally { HttpListener = null; } logger?.LogInformation("HttpListener for requests on {0} FINISHED", string.Join(", ", UriPrefixes)); }
public static object Request(RequestType what, RequestProperty want) { object r; r = OnRequest?.Invoke(what, want); return(r); }
private static void ConfigureRejuicer() { OnRequest.ForJs("~/Combined-{0}.js").Combine .File("~/Scripts/jquery-1.7.2.js") .File("~/Scripts/jquery-ui-1.8.19") .File("~/Scripts/jquery.mobile-1.1.0") .File("~/Scripts/jquery.unobtrusive-ajax.js") .File("~/Scripts/jquery.validate.js") .File("~/Scripts/jquery.validate.unobtrusive.js") .File("~/Scripts/SyntaxHighlighter/shCore.js") .File("~/Scripts/SyntaxHighlighter/shBrushBash.js") .File("~/Scripts/SyntaxHighlighter/shBrushCss.js") .File("~/Scripts/SyntaxHighlighter/shBrushCSharp.js") .File("~/Scripts/SyntaxHighlighter/shBrushJScript.js") .File("~/Scripts/SyntaxHighlighter/shBrushPowerShell.js") .File("~/Scripts/SyntaxHighlighter/shBrushRuby.js") .File("~/Scripts/SyntaxHighlighter/shBrushSql.js") .File("~/Scripts/SyntaxHighlighter/shBrushXml.js") .File("~/Scripts/modernizr-2.5.3.js") .File("~/Scripts/FileUploader/fileuploader.js") .File("~/Scripts/mblog/mblog.js") .Configure(); OnRequest.ForCss("~/Combined-{0}.css").Compact .File("~/Content/Styles/reset.css") .File("~/Content/SyntaxHighlighter/shCore.css") .File("~/Content/SyntaxHighlighter/shThemeRDark.css") .File("~/Content/fileuploader/fileuploader.css") .Configure(); }
/// <summary> /// This method is called to process an incoming payload. /// </summary> /// <param name="rq">The message to process.</param> /// <param name="responses">The return path for the message.</param> public virtual async Task ProcessRequest(TransmissionPayload rq, List <TransmissionPayload> responses) { int start = StatisticsInternal.ActiveIncrement(); try { var header = rq.Message.ToServiceMessageHeader(); H handler; if (!SupportedResolve(header, out handler)) { OnRequestUnresolved?.Invoke(this, rq); throw new CommandNotSupportedException(rq.Id, header, GetType()); } OnRequest?.Invoke(this, rq); //Call the registered command. await handler.Execute(rq, responses); } catch (Exception) { StatisticsInternal.ErrorIncrement(); //throw any errors back out to the dispatcher. throw; } finally { StatisticsInternal.ActiveDecrement(start); } }
public void ReadCallback(IAsyncResult ar) { var state = (HubState)ar.AsyncState; var bytesRead = state.WorkSocket.EndReceive(ar); if (bytesRead <= 0) { return; } bool recv; try { recv = state.Receive(bytesRead); } catch (Exception e) { state.SendError(e); recv = true; } if (recv) { OnRequest?.Invoke(this, state); Send(state); } else { state.WorkSocket.BeginReceive(state.Buffer, state.BufferLen, Config.BufferSize, 0, ReadCallback, state); } }
public void FluentConfiguration_Configure_AddsRejuicerModelToConfiguration() { OnRequest.ForJs("~/Scripts/Combined-Test.js").Combine .FilesIn("~/Scripts/").Matching("*.js").Configure(); Assert.AreEqual(1, RejuicerEngine._configurations.Count); }
private async void ListenAsyncImpl() { //if this method fails due to an access denied error, run visual studio as an administrator _listener.Start(); while (_listener.IsListening) { HttpListenerContext ctx = null; try { ctx = await _listener.GetContextAsync().ConfigureAwait(false); } catch (HttpListenerException e) { OnError?.Invoke(this, e); } if (ctx == null) { return; } OnRequest?.Invoke(this, ctx); } }
public Website(string[] prefixes, OnRequest request) { this.Prefixes = prefixes; this.onRequest = request; issipmle = false; }
void ProcessRequest(HttpListenerContext context, OnRequest callback) { var request = context.Request; var response = context.Response; string outputHtml = null; try // ユーザ処理でコケたら500返す。それ以外は200にしちゃってるがマズければ番号ももらうようにした方がいいのかも。 { var bodyData = request.InputStream; callback(out outputHtml, request.QueryString, bodyData); bodyData.Close(); if (outputHtml != null) { var outputData = System.Text.Encoding.UTF8.GetBytes(outputHtml); response.Close(outputData, willBlock: false); } else { response.Close(); } } catch (System.Exception e) { Debug.LogException(e); response.StatusCode = (int)HttpStatusCode.InternalServerError; response.Close(); } }
// For recieving and sending replies to host as far as I can tell private static bool ApiReceiver(SoapAPI api) { try { // Based on what myApi.MessageType is switch (api.MessageType) { case MessageTypes.Request: // Did we recieve a request for a reply from the host? OnRequest?.Invoke(api, new VmsRequestEventArgs { Request = new VmsCommand(api) }); break; case MessageTypes.Reply: // Did we recieve a reply from the host? OnReply?.Invoke(api, new VmsReplyEventArgs { Reply = new VmsCommand(api) }); break; default: break; } return(true); } catch (Exception ex) { //MessageBox.Show("Error: " + ex.ToString()); return(false); } }
/// <summary> /// Process a request. /// </summary> /// <param name="context"></param> private void Process(HttpListenerContext context) { OnRequest?.Invoke(context.Request); var filename = context.Request.Url.AbsolutePath.Substring(1); if (string.IsNullOrEmpty(filename)) { foreach (var indexFile in indexFiles) { if (!File.Exists(Path.Combine(root, indexFile))) { continue; } filename = indexFile; break; } } filename = Path.Combine(root, filename); string mime; if (File.Exists(filename) && mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime)) { try { Stream input = new FileStream(filename, FileMode.Open); context.Response.ContentType = mime; context.Response.ContentLength64 = input.Length; context.Response.AddHeader("Date", DateTime.Now.ToString("r")); context.Response.AddHeader("Last-Modified", File.GetLastWriteTime(filename).ToString("r")); int nbytes; byte[] buffer = new byte[1024 * 16]; while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0) { context.Response.OutputStream.Write(buffer, 0, nbytes); } input.Close(); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.OutputStream.Flush(); } catch { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } } else { context.Response.StatusCode = (int)HttpStatusCode.NotFound; } context.Response.OutputStream.Close(); }
void ProcessRequest(HttpListenerContext context) { UnityEngine.Profiling.Profiler.BeginSample("DebugServer.ProcessRequest"); var request = context.Request; var path = DebugServerUtil.RemoveQueryString(request.RawUrl); // QueryStringいらない if (path.StartsWith(fileService.pathPrefix)) { Debug.Log("FileService.ProcessReq"); fileService.ProcessRequest(context); } else { OnRequest callback = null; if (callbacks.TryGetValue(path, out callback)) { ProcessRequest(context, callback); } else { var response = context.Response; response.StatusCode = 404; response.Close(); } } UnityEngine.Profiling.Profiler.EndSample(); }
public static void HasConfigurationFor_WithOneLambdaPlaceholderConfigurationNotMatching_DoesNotMatch() { OnRequest.ForCss(x => "~/TestFile-" + x + ".css") .Compact .Configure(); Assert.IsFalse(RejuicerEngine.HasConfigurationFor("~/OtherFile-{0}.css")); }
public static void HasConfigurationFor_WithOnePlaceholderConfigurationMatching_Matches() { OnRequest.ForCss("~/TestFile-{0}.css") .Compact .Configure(); Assert.IsTrue(RejuicerEngine.HasConfigurationFor("~/TestFile-{0}.css")); }
public static void HasConfigurationFor_WithNoPlaceholderConfigurations_DoesNotMatchPlaceholder() { OnRequest.ForCss("~/TestFile.css") .Compact .Configure(); Assert.IsFalse(RejuicerEngine.HasConfigurationFor("~/TestFile{0}.css")); }
public static void HasConfigurationFor_WithOneConfigurationNotMatching_NoMatch() { OnRequest.ForCss("~/TestFile.css") .Compact .Configure(); Assert.IsFalse(RejuicerEngine.HasConfigurationFor("~/OtherFile.css")); }
protected override void ProcessRequest(HttpRequest request) { OnRequest?.Invoke(request); if (OnRequest.GetInvocationList().Length == 0) { request.Respond("This request is not handled.", System.Net.HttpStatusCode.BadRequest); } }
public void FluentConfiguration_File_AddsFileToConfig() { var config = GetModelFor(OnRequest.ForJs("~/Scripts/Combined-Test.js").Combine .File("~/Scripts/myfile.js")); Assert.AreEqual(1, config.Count); Assert.AreEqual("~/Scripts/myfile.js", ((PhysicalFileSource)config[0]).VirtualPath); }
public TransferAnswer SendRequest(TransferRequest request) { var src = request.Source; var dst = request.Destination; OnRequest?.Invoke(this, EventArgs.Empty); return(new TransferAnswer()); }
protected override Task Process(HttpListenerContext context, ILogger logger, CancellationToken cancellation) { if (OnRequest != null) { return(OnRequest.Invoke(context, cancellation)); } return(base.Process(context, logger, cancellation)); }
private void Listen() { Console.WriteLine("Started listening on {0}", Address); while (listener.IsListening) { var context = listener.GetContext(); OnRequest?.Invoke(this, context); } Console.WriteLine("Stopped listening"); }
/// <summary>收到客户端发来的数据。子类可通过重载该方法来修改数据</summary> /// <param name="e"></param> protected override void OnReceive(ReceivedEventArgs e) { // 解析请求头 var stream = e.Packet.GetStream(); var entity = HttpHeader.Read(stream, HttpHeaderReadMode.Request); if (entity == null) { base.OnReceive(e); return; } WriteLog("{3}请求:{0} {1} [{2}]", entity.Method, entity.Url, entity.ContentLength, ID); Request = entity; OnRequest?.Invoke(this, e); var pxy = Host as HttpReverseProxy; var host = entity.Url.IsAbsoluteUri ? entity.Url.Host : pxy.RemoteServer.Host; RemoteHost = host; RawHost = entity.Host; entity.Host = host; // 引用 var r = entity.Referer; if (!String.IsNullOrEmpty(r)) { var ri = new Uri(r, UriKind.RelativeOrAbsolute); if (ri.IsAbsoluteUri && ri.Authority == RawHost) { r = r.Replace(RawHost, host); entity.Referer = r; } } //// 取消压缩 //var key = "Accept-Encoding"; //if (entity.Headers.ContainsKey(key)) entity.Headers.Remove(key); // 重新构造请求 var ms = new MemoryStream(); entity.Write(ms); stream.CopyTo(ms); ms.Position = 0; //e.Stream = ms; e.Packet = ms.ToArray(); base.OnReceive(e); }
private void RequestOneTimeToken(OnRequest request, string cardNumber, string expMonth, string expYear, string cvv) { WWWForm form = new WWWForm(); form.AddField("public_key", this.publicKey); form.AddField("card[number]", cardNumber); form.AddField("card[exp_month]", expMonth); form.AddField("card[exp_year]", "20" + expYear); form.AddField("card[cvv]", cvv); WWW www = new WWW(PWBase.TOKEN_URL, form); StartCoroutine(request(www)); }
private void onMessage(object sender, MessageEventArgs e) { Log.Trace("onMessage: " + e.Data); if (e.IsText) { var command = CommandBase.FromJson(e.Data); var receivers = OnRequest.GetInvocationList(); foreach (EventHandler <CommandBase> receiver in receivers) { OnRequest?.BeginInvoke(this, command, null, null); } } }
/// <summary> /// 监听到请求时 /// </summary> private void ListenedRequest(IAsyncResult result) { var context = listener.EndGetContext(result); if (OnRequest != null) { try { OnRequest.Invoke(context); } catch { } } listener.BeginGetContext(ListenedRequest, null); }
public static void Configure() { OnRequest.ForJs("~/Combined-{0}.js") .Compact .FilesIn("~/Scripts/") .Matching("*.js") .Configure(); OnRequest.ForCss("~/Combined.css") .Compact .FilesIn("~/Styles/") .Matching("*.css") .Configure(); }
private void SendCallback(IAsyncResult ar) { var state = (AgentState)ar.AsyncState; try { state.WorkSocket.EndSend(ar); SendDone.Set(); OnRequest?.Invoke(this, state); } catch (Exception e) { Abort(state, e); } }
public void FluentConfiguration_File_IncludesWildCardFiles() { var configurator = OnRequest.ForJs("~/Scripts/Combined-Test.js") .Combine .FilesIn("~/Scripts/") .Matching("*.js"); configurator.Configure(); var model = GetModelFor(configurator); Assert.AreEqual(1, RejuicerEngine._configurations.Count); Assert.AreEqual(3, model.Count); Assert.AreEqual("~/Scripts/one.js", ((PhysicalFileSource)model[0]).VirtualPath); Assert.AreEqual("~/Scripts/three.js", ((PhysicalFileSource)model[1]).VirtualPath); Assert.AreEqual("~/Scripts/two.js", ((PhysicalFileSource)model[2]).VirtualPath); }
private void RequestCharge(OnRequest request, string token) { WWWForm form = new WWWForm(); var headers = form.headers; headers ["X-ApiKey"] = this.privateKey; form.AddField("token", token, Encoding.UTF8); form.AddField("amount", this.amount.ToString()); form.AddField("currency", this.currency); form.AddField("email", txtEmail.text); form.AddField("fingerprint", "your fingerprint here"); form.AddField("description", "your description here"); WWW www = new WWW(PWBase.GetChargeURL(), form.data, headers); StartCoroutine(request(www)); }
private async Task ProcessTranslation(HttpListenerRequest req, HttpListenerResponse resp) { string?japanese = GetTextParam(req); OnRequest?.Invoke(req.RemoteEndPoint, japanese); if (japanese == null) { return; } string?korean = await Translator.Translate(japanese ?? "").ConfigureAwait(false); resp.ContentType = "text/plain; charset=utf-8"; byte[] buf = Encoding.UTF8.GetBytes(korean); resp.ContentLength64 = buf.LongLength; await resp.OutputStream.WriteAsync(buf, 0, buf.Length); }