internal static void Register (ServerContext context)
		{
			for (int i = 0; i < 100; i++) {
				var id = random.Next ();
				if ((id == 0) || ctxById.ContainsKey (id))
					continue;

				context.id = id;
				ctxById [id] = context;

				var response = context.ListenerContext.Response;
				response.AddHeader (HeaderName, id.ToString ());
				return;
			}
			throw new InvalidOperationException ();
		}
Exemple #2
0
		async Task Run ()
		{
			var context = await listener.GetContextAsync ();
			var url = context.Request.Url;

			var path = url.AbsolutePath.Substring (1);
			if (path == string.Empty) {
				PrintIndex (context);
				context.Response.Close ();
				return;
			} else if (path.Equals ("favicon.ico")) {
				context.Response.StatusCode = 404;
				context.Response.Close ();
				return;
			}

			if (!handlerByName.ContainsKey (path)) {
				Log ("Unknown URL: {0}", path);
				Error (context.Response, "Invalid URL: '{0}'", path);
				return;
			}

			var handler = handlerByName [path];

			var sctx = new ServerContext (context);
			if (handler.IsAsync)
				ServerContext.Register (sctx);
			try {
				await sctx.Invoke (handler.Name, handler.Method);
			} catch (Exception ex) {
				if (!sctx.SetException (ex))
					Exception (context.Response, ex);
			} finally {
				try {
					context.Response.Close ();
				} catch {
					;
				}
			}
		}