本文整理汇总了C#中System.Net.HttpListener.Start方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.Start方法的具体用法?C# HttpListener.Start怎么用?C# HttpListener.Start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpListener
的用法示例。
在下文中一共展示了HttpListener.Start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ApiManager
public ApiManager()
{
string hostName = Dns.GetHostName();
string IP = Dns.GetHostByName(hostName).AddressList[0].ToString();
string DebugPort = ConfigurationManager.AppSettings["DebugPort"];
m_vListener = new HttpListener();
if (Convert.ToBoolean(ConfigurationManager.AppSettings["DebugModeLocal"]))
{
m_vListener.Prefixes.Add("http://localhost:" + DebugPort + "/debug/");
//m_vListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
m_vListener.Start();
Console.WriteLine("API Manager started on http://localhost:" + DebugPort + "/debug/");
Action action = RunServer;
action.BeginInvoke(RunServerCallback, action);
}
else
{
string DebugMode = IP + ":";
m_vListener.Prefixes.Add("http://" + DebugMode + DebugPort + "/debug/");
//m_vListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
m_vListener.Start();
Console.WriteLine("API Manager started on http://" + IP + ":" + DebugPort + "/debug/");
Action action = RunServer;
action.BeginInvoke(RunServerCallback, action);
}
}
示例2: AssembyInitialize
public static void AssembyInitialize(TestContext testcontext)
{
listener = new HttpListener();
listener.Prefixes.Add("http://+:" + Port + WebSocketConstants.UriSuffix + "/");
listener.Start();
RunWebSocketServer().Fork();
}
示例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: Main
// initialize git repo as follow
// > mkdir repository
// > cd repository
// > git init .
// > git config receive.denyCurrentBranch ignore
static void Main(string[] args)
{
if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.Unix)
{
GitExe = "/usr/bin/git";
}
try
{
RepositoryPath = args[0];
var port = Int32.Parse(args[1]);
string prefix = String.Format("http://localhost:{0}/", port);
var listener = new HttpListener();
listener.Prefixes.Add(prefix);
listener.Start();
Console.WriteLine("Listening at " + prefix);
while (true)
{
// simple handle one request at a time
ProcessRequest(listener.GetContext());
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
示例5: Start
public void Start()
{
httpListener = new HttpListener();
httpListener.Prefixes.Add("http://localhost:" + this.ListenPort + "/");
httpListener.Start();
httpListener.BeginGetContext(this.OnNewRequest, null);
}
示例6: 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);
}
}
}
});
}
示例7: Start
public void Start()
{
logger = LoggerFactory.GetLogger("SimpleHttpServer.Server");
logger.Info("Server starting on port {0}", port);
if (listener != null)
{
logger.Fatal("Server already started");
throw new InvalidOperationException("Already started");
}
listener = new HttpListener();
listener.Prefixes.Add(string.Format("http://*:{0}/", port));
try
{
listener.Start();
}
catch(Exception ex)
{
logger.Fatal("Error starting server", ex);
throw;
}
logger.Info("Server started");
logger.Debug("Waiting for first request");
listener.BeginGetContext(ProcessRequest, null);
}
示例8: Listen
public void Listen() {
if (!HttpListener.IsSupported) {
throw new System.InvalidOperationException(
"使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
}
string[] prefixes = new string[] { host };
listener = new HttpListener();
foreach (string s in prefixes) {
listener.Prefixes.Add(s);
}
listener.Start();
while (is_active) {
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
Console.WriteLine("User-Agent: {0}", request.UserAgent);
Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
Console.WriteLine("Connection: {0}", request.KeepAlive ? "Keep-Alive" : "close");
Console.WriteLine("Host: {0}", request.UserHostName);
HttpListenerResponse response = context.Response;
if (request.HttpMethod == "GET") {
OnGetRequest(request, response);
} else {
OnPostRequest(request, response);
}
}
}
示例9: Main
static void Main(string[] args)
{
if(args.Length != 1)
{
Console.Error.WriteLine("Usage: name port");
return;
}
int port;
if(!int.TryParse(args[0], out port))
{
Console.Error.WriteLine("Invalid port");
return;
}
var listener = new HttpListener();
listener.Prefixes.Add(string.Format("http://+:{0}/sort/", port));
listener.Start();
while(true)
{
SolveAsync(listener.GetContext());
}
}
示例10: Main
static void Main(string[] args)
{
try
{
dbaddr = db.confreader.getservers(true);
listener = new HttpListener();
listener.Prefixes.Add("http://*:" + port + "/");
listener.Start();
listen = new Thread(ListenerCallback);
listen.Start();
for (var i = 0; i < workers.Length; i++)
{
workers[i] = new Thread(Worker);
workers[i].Start();
}
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Terminating...");
listener.Stop();
while (contextQueue.Count > 0)
Thread.Sleep(100);
Environment.Exit(0);
};
Console.WriteLine("Listening at port " + port + "...");
Thread.CurrentThread.Join();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.ToString());
Console.ReadLine();
}
}
示例11: DetergentHttpListener
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);
}
示例12: Listen
public async Task Listen(string prefix, int maxConcurrentRequests, CancellationToken token)
{
HttpListener listener = new HttpListener();
try
{
listener.Prefixes.Add(prefix);
listener.Start();
var requests = new HashSet<Task>();
for (int i = 0; i < maxConcurrentRequests; i++)
requests.Add(listener.GetContextAsync());
while (!token.IsCancellationRequested)
{
Task t = await Task.WhenAny(requests);
requests.Remove(t);
if (t is Task<HttpListenerContext>)
{
var context = (t as Task<HttpListenerContext>).Result;
requests.Add(ProcessRequestAsync(context));
requests.Add(listener.GetContextAsync());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
示例13: HttpServer
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");
}
示例14: SendEmptyData_Success
public async Task SendEmptyData_Success()
{
using (HttpListener listener = new HttpListener())
{
listener.Prefixes.Add(ServerAddress);
listener.Start();
Task<HttpListenerContext> serverAccept = listener.GetContextAsync();
WebSocketClient client = new WebSocketClient();
Task<WebSocket> clientConnect = client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None);
HttpListenerContext serverContext = await serverAccept;
Assert.True(serverContext.Request.IsWebSocketRequest);
HttpListenerWebSocketContext serverWebSocketContext = await serverContext.AcceptWebSocketAsync(null);
WebSocket clientSocket = await clientConnect;
byte[] orriginalData = new byte[0];
await clientSocket.SendAsync(new ArraySegment<byte>(orriginalData), WebSocketMessageType.Binary, true, CancellationToken.None);
byte[] serverBuffer = new byte[orriginalData.Length];
WebSocketReceiveResult result = await serverWebSocketContext.WebSocket.ReceiveAsync(new ArraySegment<byte>(serverBuffer), CancellationToken.None);
Assert.True(result.EndOfMessage);
Assert.Equal(orriginalData.Length, result.Count);
Assert.Equal(WebSocketMessageType.Binary, result.MessageType);
Assert.Equal(orriginalData, serverBuffer);
clientSocket.Dispose();
}
}
示例15: LdtpdService
LdtpdService()
{
if (!String.IsNullOrEmpty(ldtpDebugEnv))
debug = true;
if (String.IsNullOrEmpty(ldtpPort))
ldtpPort = "4118";
common = new Common(debug);
windowList = new WindowList(common);
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:" + ldtpPort + "/");
listener.Prefixes.Add("http://+:" + ldtpPort + "/");
// Listen on all possible IP address
if (listenAllInterface != null && listenAllInterface.Length > 0)
{
if (debug)
Console.WriteLine("Listening on all interface");
listener.Prefixes.Add("http://*:" + ldtpPort + "/");
}
else
{
// For Windows 8, still you need to add firewall rules
// Refer: README.txt
if (debug)
Console.WriteLine("Listening only on local interface");
}
listener.Start();
svc = new Core(windowList, common, debug);
}