本文整理汇总了C#中System.Net.HttpListener.GetContext方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.GetContext方法的具体用法?C# HttpListener.GetContext怎么用?C# HttpListener.GetContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpListener
的用法示例。
在下文中一共展示了HttpListener.GetContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: startListener
public void startListener()
{
listener = new HttpListener();
listener.Prefixes.Add(prefix); // プレフィックスの登録
listener.Start();
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest req = context.Request;
HttpListenerResponse res = context.Response;
Console.WriteLine(req.RawUrl);
// リクエストされたURLからファイルのパスを求める
string path = root + req.RawUrl.Replace("/", "\\");
// ファイルが存在すればレスポンス・ストリームに書き出す
if (File.Exists(path))
{
byte[] content = File.ReadAllBytes(path);
res.OutputStream.Write(content, 0, content.Length);
}
res.Close();
}
}
示例2: Start
public void Start()
{
if (!started)
{
listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
started = true;
while (true)
{
Console.WriteLine("waiting....");
HttpListenerContext context = listener.GetContext();
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(content);
context.Response.StatusCode = (int) HttpStatusCode.OK;
using (var stream = context.Response.OutputStream)
{
using (var writer = new StreamWriter(stream))
{
writer.Write(content);
}
}
Console.WriteLine("message sent....");
}
}
else
{
Console.WriteLine("server already started");
}
}
示例3: Run
public override void Run()
{
Trace.WriteLine("WorkerRole entry point called", "Information");
HttpListener listener = new HttpListener();
IPEndPoint inputEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HelloWorldEndpoint"].IPEndpoint;
string listenerPrefix = string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}/", inputEndPoint.Address, inputEndPoint.Port);
Trace.WriteLine("Listening to -" + listenerPrefix);
listener.Prefixes.Add(listenerPrefix);
listener.Start();
while (true)
{
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
//Close the output stream.
output.Close();
}
}
示例4: OpenFakeHttpServer
private static void OpenFakeHttpServer(int port)
{
Console.WriteLine($"Openning port {port}");
int i = 0;
var li = new HttpListener();
li.Prefixes.Add($"http://+:{port}/api/");
li.Start();
Task.Factory.StartNew(() =>
{
while (true)
{
var ctx = li.GetContext();
using (ctx.Response)
{
ctx.Response.SendChunked = false;
ctx.Response.StatusCode = 200;
Console.WriteLine($"at {port} Correlation {ctx.Request.Headers["X-CORRELATION"]}");
using (var sw = new StreamWriter(ctx.Response.OutputStream))
{
++i;
var str = $"{i}!!!";
ctx.Response.ContentLength64 = str.Length;
sw.Write(str);
}
}
}
});
}
示例5: ShouldConfigure
public void ShouldConfigure()
{
XmlConfigurator.Configure();
ILog logger = LogManager.GetLogger(typeof(HttpAppenderTests));
using (var listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost:34343/");
listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
listener.Start();
try
{
throw new Exception("KABOOM!");
}
catch (Exception e)
{
logger.Error("Oh noes!", e);
}
var ctx = listener.GetContext();
using (var reader = new StreamReader(ctx.Request.InputStream))
{
var body = reader.ReadToEnd();
Console.WriteLine(body);
Assert.IsNotNull(body);
HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)ctx.User.Identity;
Assert.AreEqual("derp", identity.Name);
Assert.AreEqual("darp", identity.Password);
}
ctx.Response.Close();
}
}
示例6: AddTask
public static void AddTask(HttpListener listener)
{
var context = listener.GetContext();
tasks.Add(Task.Factory.StartNew(
() =>
{
var request = context.Request;
var stream = request.InputStream;
var query = request.Url.Query;
var response = context.Response;
if (requests.ContainsKey(query))
SendResponse(response, requests[query]);
else
{
var regex = new Regex(@".query=.");
lock (requests)
{
if (regex.IsMatch(query))
ProcessRequest(response, query);
}
}
}
));
}
示例7: StartRun
protected override void StartRun()
{
_listener = new HttpListener();
#if !UNSAFE
try
{
#endif
_listener.Prefixes.Add("http://*:" + (Settings.Instance.WebServerPort) + "/");
try
{
_listener.Start();
}
catch (HttpListenerException ex)
{
#if WINDOWS
if (ex.NativeErrorCode == 5)
{
Log.Fatal(@"TO GET XG UP AND RUNNING YOU MUST RUN 'netsh http add urlacl url=http://*:5556/ user=%USERDOMAIN%\%USERNAME%' AS ADMINISTRATOR");
}
#endif
throw;
}
var fileLoader = new FileLoader {Salt = Salt};
while (_allowRunning)
{
#if !UNSAFE
try
{
#endif
var connection = new BrowserConnection
{
Context = _listener.GetContext(),
Servers = Servers,
Files = Files,
Searches = Searches,
Snapshots = Snapshots,
FileLoader = fileLoader,
Password = Password,
Salt = Salt
};
connection.Start();
#if !UNSAFE
}
catch (HttpListenerException)
{
// this is ok
}
#endif
}
#if !UNSAFE
}
catch (HttpListenerException)
{
// this is ok
}
#endif
}
示例8: Start
public void Start(int port)
{
_listener = _listener ?? InitializeListenerOnPort(port);
_listener.Start();
_task = new CancellationTokenSource();
Task.Factory.StartNew(() =>
{
while (!_task.IsCancellationRequested)
{
try
{
var context = _listener.GetContext();
ThreadPool.QueueUserWorkItem(_ => HandleContext(context));
}
catch (HttpListenerException e)
{
if (e.ErrorCode == GetContextInterrupted)
{
// The receiver has been stopped. Return.
return;
}
throw;
}
}
}, _task.Token);
}
示例9: Run
/// <summary>
/// Запускает сервер, стартует все приложения внутри сервера
/// </summary>
public void Run()
{
using (HttpListener listener = new HttpListener ())
{
listener.Prefixes.Add (string.Format ("http://{0}:{1}/", _settings.Host, _settings.Port));
foreach (var app in _apps)
{
string prefix = string.Format ("http://{0}:{1}{2}", _settings.Host, _settings.Port, app.Path);
listener.Prefixes.Add (prefix);
Logger.Info ("Application added on: '{0}'", prefix);
}
listener.Start ();
Logger.Info ("HTTPListener started at '{0}:{1}'", _settings.Host, _settings.Port);
while (!_disposed.WaitOne(TimeSpan.FromMilliseconds(10)))
{
var context = listener.GetContext();
ProcessRequest(context);
}
listener.Stop ();
Logger.Info ("HTTPListener stopped at '{0}:{1}'", _settings.Host, _settings.Port);
}
}
示例10: Run
public void Run()
{
try
{
Trace.WriteLine("Starting Windows VM Service");
HttpListener listener = new HttpListener();
listener.Prefixes.Add(ListenerPrefix);
listener.Start();
while (true)
{
try
{
HttpListenerContext ctx = listener.GetContext();
RequestHandler handler = new RequestHandler(ctx, mAccountsManager);
handler.ProcessRequest();
}
catch (Exception ex)
{
Trace.WriteLine("Exception caught: " + ex.Message + "\n" + ex.StackTrace);
}
}
}
catch (Exception e)
{
Trace.WriteLine("Exception caught @ run: " + e.Message);
}
}
示例11: Listener
static void Listener ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:8081/");
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
listener.Start ();
int requestNumber = 0;
while (true) {
HttpListenerContext ctx = listener.GetContext ();
Stream input = ctx.Request.InputStream;
StreamReader sr = new StreamReader (input, ctx.Request.ContentEncoding);
sr.ReadToEnd ();
ctx.Response.ContentLength64 = 0;
ctx.Response.StatusCode = 204;
ctx.Response.StatusDescription = "No Content";
ctx.Response.Close ();
requestNumber++;
if (requestNumber == Count)
break;
}
}
示例12: Main
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:1234/");
listener.Prefixes.Add("http://127.0.0.1:1234/");
listener.Prefixes.Add("http://192.168.56.102:1234/");
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
string responseString = getCryptoResponse();
byte[] buffer = System.Text.Encoding.Unicode.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
}
listener.Stop();
}
示例13: Servicio
private static void Servicio()
{
MyExeHost myHost = (MyExeHost)ApplicationHost.CreateApplicationHost(typeof(MyExeHost), "/", Environment.CurrentDirectory + "\\elWeb");
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8081/");
listener.Prefixes.Add("http://127.0.0.1:8081/");
listener.Start();
while (true)
{
try
{
HttpListenerContext ctx = listener.GetContext();
string page = ctx.Request.Url.LocalPath.Replace("/", "");
string query = ctx.Request.Url.Query.Replace("?", "");
StreamWriter sw = new
StreamWriter(ctx.Response.OutputStream);
myHost.ProcessRequest(page, query, sw);
sw.Flush();
ctx.Response.Close();
}
catch (Exception ex) { }
}
}
示例14: start
public static void start(int port, string adress)
{
string[] prefixes = {"http://*"+":"+port+"/"};
if (!HttpListener.IsSupported){
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use this program.");
return;
}
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes){
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
Console.Title = "WebS - Listening on *:"+port;
while(true){
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
//Console.Write(request.RawUrl);
if(checkFile("./web"+request.RawUrl) == "E404"){
TextHelper.writeInfo("Connection from "+request.RemoteEndPoint+" on "+request.RawUrl);
TextHelper.writeErr(request.RemoteEndPoint+" tried to access "+request.RawUrl+" but it doesn't exist! (404)");
writeRes(response, "<HTML><BODY>404 NOT FOUND</BODY></HTML>");
}else{
TextHelper.writeInfo("Connection from "+request.RemoteEndPoint+" on "+request.RawUrl);
writeRes(response, checkFile("./web"+request.RawUrl));
}
}
}
示例15: Main
static void Main(string[] args)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
//listener.Prefixes.Add("http://192.168.1.3:8081/");
listener.Start();
Console.WriteLine("Listening...");
HttpListenerContext context = listener.GetContext();
HttpListenerResponse response = context.Response;
HttpListenerRequest request = context.Request;
string s = request.RemoteEndPoint.Address.MapToIPv4().ToString();
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
Console.WriteLine("Richiesta da {0}", s);
Console.ReadLine();
}