本文整理汇总了C#中HttpListener.GetContext方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.GetContext方法的具体用法?C# HttpListener.GetContext怎么用?C# HttpListener.GetContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpListener
的用法示例。
在下文中一共展示了HttpListener.GetContext方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartListener
public void StartListener (Object args)
{
HttpListener listener = new HttpListener ();
string prefix = string.Format ("http://*:8880/{0}/", args);
listener.Prefixes.Add (prefix);
listener.Start ();
for (; ; ) {
HttpListenerContext ctx = listener.GetContext ();
new Thread (new Worker (ctx).ProcessRequest).Start ();
}
}
示例2: Listen
private static void Listen ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:8080/a/");
listener.Start ();
HttpListenerResponse response = listener.GetContext().Response;
response.ContentType = "text/xml";
byte [] buffer = Encoding.UTF8.GetBytes ("<ok/>");
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write (buffer, 0, buffer.Length);
output.Close ();
listener.Stop ();
}
示例3: Main
static int Main ()
{
TinyHost h = CreateHost ();
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://" + IPAddress.Loopback.ToString () + ":8081/");
listener.Start ();
HttpListenerContext ctx = listener.GetContext ();
StreamWriter sw = new StreamWriter (ctx.Response.OutputStream);
h.Execute ("FaultService.asmx", sw);
sw.Flush ();
ctx.Response.Close ();
return 0;
}
示例4: Main
static void Main(string[] args)
{
var port = "1982";
var root = ".";
var prefix = String.Format("http://*:{0}/", port);
Log("listening {0}", prefix);
var listener = new HttpListener();
listener.Prefixes.Add(prefix);
listener.Start();
while (true) {
var context = listener.GetContext();
var request = context.Request;
var response = context.Response;
Log("{0} {1}", request.HttpMethod, request.RawUrl);
if (request.RawUrl == "/api") {
ApiResponse(response, request);
}
else {
var path = root + request.RawUrl;
try {
var content = File.ReadAllBytes(path);
response.ContentType = "text/plain";
response.AppendHeader("Content-Length", content.Length.ToString());
response.OutputStream.Write(content, 0, content.Length);
}
catch (FileNotFoundException e) {
ErrorResponse(response, 404, e);
}
catch (UnauthorizedAccessException e) {
ErrorResponse(response, 403, e);
}
catch (Exception e) {
ErrorResponse(response, 500, e);
}
}
Log(" -> {0}", response.StatusCode);
response.Close();
}
}
示例5: run_server
static void run_server ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add (url);
listener.Start ();
while (server_count < count) {
HttpListenerContext context = listener.GetContext ();
HttpListenerResponse response = context.Response;
string responseString = "my data";
byte [] buffer = Encoding.UTF8.GetBytes (responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write (buffer, 0, buffer.Length);
output.Close ();
server_count++;
}
}
示例6: Main
//用户可能需要具有管理员身份才能运行此应用程序
static void Main()
{
var listener = new HttpListener();
listener.Prefixes.Add("http://+:8086/csharpfeeds/");
listener.Start();
// 打开指向将为其提供服务的源的浏览器。
string uri = @"http://localhost:8086/csharpfeeds/";
System.Diagnostics.Process browser = new System.Diagnostics.Process();
browser.StartInfo.FileName = "iexplore.exe";
browser.StartInfo.Arguments = uri;
browser.Start();
// 为请求提供服务。
while (true) {
var context = listener.GetContext();
var body = GetReplyBody();
context.Response.ContentType = "text/xml";
using (XmlWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
body.WriteTo(writer);
}
}
示例7: Main
static void Main(string []args)
{
if(args.Length != 2)
{
Console.WriteLine("Error: please specify URI to listen on and Authentication type to use:\nAuthListener.exe ServerURI AuthenticationScheme");
return;
}
string serverUri = args[0];
AuthenticationSchemes authScheme;
switch(args[1].ToLower())
{
case "none":
authScheme = AuthenticationSchemes.None;
break;
case "anonymous":
authScheme = AuthenticationSchemes.Anonymous;
break;
case "basic":
authScheme = AuthenticationSchemes.Basic;
break;
case "digest":
authScheme = AuthenticationSchemes.Digest;
break;
case "ntlm":
authScheme = AuthenticationSchemes.Ntlm;
break;
case "negotiate":
authScheme = AuthenticationSchemes.Negotiate;
break;
case "integrated":
authScheme = AuthenticationSchemes.IntegratedWindowsAuthentication;
break;
default:
Console.WriteLine("Error: unrecognized AuthenticationScheme:{0}", args[1]);
return;
}
HttpListener listener = new HttpListener();
listener.Prefixes.Add(serverUri);
listener.AuthenticationSchemes = authScheme;
listener.Start();
Console.WriteLine("Listening...");
HttpListenerContext context = listener.GetContext();
Console.WriteLine("Received request...");
StreamWriter writer = new StreamWriter(context.Response.OutputStream);
// Verify correct authentication scheme was used.
if (!VerifyAuthenticationScheme(listener.AuthenticationSchemes, context))
{
context.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;
writer.Write("Error authentication validation failed");
}
context.Response.Close();
}
示例8: Run
public void Run()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
// Wait for a request
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// process the request
string path = request.Url.AbsolutePath;
string responseString;
try
{
responseString = handler(context);
}
catch (Exception e)
{
responseString = e.ToString();
}
// write the response
HttpListenerResponse response = context.Response;
System.IO.Stream output = response.OutputStream;
if (!String.IsNullOrEmpty(responseString))
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
output.Write(buffer, 0, buffer.Length);
}
output.Close();
// shut down the listener
listener.Stop();
}
示例9: ListenThread
private void ListenThread()
{
try
{
listener = new HttpListener();
foreach (string prefix in prefixes)
{
listener.Prefixes.Add(prefix);
}
listener.Start();
while (true)
{
HttpListenerContext context = listener.GetContext();
Debug.LogFormat("Recieved request from {0}.", context.Request.RemoteEndPoint.ToString());
context.Response.StatusCode = 200;
lock (waitingContexts)
{
waitingContexts.AddLast(context);
}
}
}
catch(Exception e)
{
Debug.LogErrorFormat("Web server error at {0}.", e.Source);
Debug.LogError(e.Message, this);
}
}
示例10: Main
static void Main(string[] args)
{
StaticStore.ReadFromFile();
StaticStore.RebuildHashTables();
DynamicStore.ReadFromFile();
var srv = new HttpListener();
srv.Prefixes.Add("http://*:23455/");
srv.Start();
using (srv) {
for (;;) {
Handle(srv.GetContext());
}
}
}
示例11: Main
public static void Main()
{
const Int32 c_port = 80;
byte[] ip = { 192, 168, 1, 222 };
byte[] subnet = { 255, 255, 255, 0 };
byte[] gateway = { 192, 168, 1, 1 };
byte[] mac = { 0x00, 0x88, 0x98, 0x90, 0xD4, 0xE0 };
WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di10,
(Cpu.Pin)FEZ_Pin.Digital.Di7, true);
NetworkInterface.EnableStaticIP(ip, subnet, gateway, mac);
NetworkInterface.EnableStaticDns(new byte[] { 192, 168, 1, 1 });
HttpListener listener = new HttpListener("http", c_port);
String file = string.Empty;
sdCard.MountFileSystem();
Debug.EnableGCMessages(false);
listener.Start();
while (true)
{
HttpListenerResponse response = null;
HttpListenerContext context = null;
HttpListenerRequest request = null;
try
{
context = listener.GetContext();
request = context.Request;
response = context.Response;
response.StatusCode = (int)HttpStatusCode.OK;
Debug.Print(request.RawUrl);
Debug.Print(request.HttpMethod);
if (request.RawUrl.Length > 1)
{
if (request.HttpMethod == "GET")
{
if (request.RawUrl =="/testtemp.jpg")
{
if (pictureTaken)
{
Debug.GC(true);
sendFile(request, response);
}
}
else
{
Debug.GC(true);
sendFile(request, response);
}
}
else if (request.HttpMethod == "POST")
{
if (request.RawUrl.CompareTo("/getPicture") == 0)
{
if (pictureTaken)
{
Thread thread = new Thread(takePicture);
thread.Start();
response.OutputStream.Write(Encoding.UTF8.GetBytes("Picture Taken"), 0, 13);
}
else
{
Byte[] aString = Encoding.UTF8.GetBytes("Picture already being taken");
response.OutputStream.Write(aString, 0, aString.Length);
}
}
}
}
else
{
string rootDirectory =
VolumeInfo.GetVolumes()[0].RootDirectory;
string[] files = Directory.GetFiles(rootDirectory);
for (int i = 0; i < files.Length; i++)
{
response.OutputStream.Write(Encoding.UTF8.GetBytes(files[i]), 0, files[i].Length);
response.OutputStream.WriteByte(10);
}
string[] folders = Directory.GetDirectories(rootDirectory);
for (int i = 0; i < folders.Length; i++)
{
Debug.Print(folders[i]);
string[] subFiles = Directory.GetFiles(folders[i]);
for (int j = 0; j < subFiles.Length; j++)
{
response.OutputStream.Write(Encoding.UTF8.GetBytes(subFiles[j]), 0, subFiles[j].Length);
response.OutputStream.WriteByte(10);
}
}
}
//We are ignoring the request, assuming GET
// Sends response:
response.Close();
context.Close();
}
catch
{
if (context != null)
//.........这里部分代码省略.........
示例12: Listen
private void Listen()
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://localhost:" + _port.ToString() + "/");
_listener.Start();
while (true)
{
try
{
HttpListenerContext context = _listener.GetContext();
Process(context);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
}
示例13: Main
public static void Main(string[] args)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
listener.Prefixes.Add("http://+:42000/");
int sessionCounter = 0;
Dictionary<int,SCXML> sessions = new Dictionary<int,SCXML>();
listener.Start();
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;
System.IO.Stream output = response.OutputStream;
String jsonBody = new StreamReader(request.InputStream).ReadToEnd();
//Dictionary<string, Dictionary<string,string>> values = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string,string>>>(jsonBody);
JObject reqJson = JObject.Parse(jsonBody);
JToken scxmlToken,eventToken,sessionJsonToken;
int sessionToken;
try{
if(reqJson.TryGetValue("load",out scxmlToken)){
Console.WriteLine("Loading new statechart");
string scxmlStr = scxmlToken.ToString();
SCXML scxml = new SCXML(new System.Uri(scxmlStr));
IList<string> initialConfiguration = scxml.Start();
sessionToken = sessionCounter++;
sessions[sessionToken] = scxml;
// Construct a response.
string responseString = TestServer.getResponseJson(sessionToken,initialConfiguration);
System.Console.WriteLine(responseString);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
output.Write(buffer,0,buffer.Length);
}else if(reqJson.TryGetValue("event",out eventToken) && reqJson.TryGetValue("sessionToken",out sessionJsonToken)){
string eventName = (string) reqJson["event"]["name"];
sessionToken = (int) reqJson["sessionToken"];
IList<string> nextConfiguration = sessions[sessionToken].Gen(eventName,null);
string responseString = TestServer.getResponseJson(sessionToken,nextConfiguration);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
output.Write(buffer,0,buffer.Length);
}else{
string responseString = "Unrecognized request.";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
output.Write(buffer,0,buffer.Length);
}
}catch(Exception e){
string responseString = "An error occured: " + e.ToString();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
output.Write(buffer,0,buffer.Length);
}
output.Close();
}
}
示例14: Listen
private void Listen()
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
_listener.Start();
while (true)
{
try
{
HttpListenerContext context = _listener.GetContext();
Process(context);
}
catch (Exception ex)
{
UnityEngine.Debug.Log(ex);
}
}
}