本文整理汇总了C#中System.Net.HttpListener.Close方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.Close方法的具体用法?C# HttpListener.Close怎么用?C# HttpListener.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpListener
的用法示例。
在下文中一共展示了HttpListener.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Disposed7
public void Disposed7 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
coll.Add ("http://127.0.0.1/");
listener.Close ();
int items = 0;
foreach (string s in coll) {
items++;
Assert.AreEqual (s, "http://127.0.0.1/");
}
Assert.AreEqual (items, 1);
}
示例2: Main
static void Main(string[] args)
{
// Create a HTTP listener.
HttpListener listener = new HttpListener();
listener.Prefixes.Add(MyEndpoint);
listener.Start(); // will abort if port not permitted and not running in Administrator mode.
try
{
ListenerLoop(listener);
Console.Write(DateTime.UtcNow + ": Listening at");
foreach (string p in listener.Prefixes)
Console.Write(" " + p);
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("Exception: Message:" + ex.Message);
}
finally
{
listener.Close();
}
}
示例3: ReplayServer
public ReplayServer(MFroReplay replay)
{
this.replay = replay;
this.alive = true;
try {
server = new HttpListener();
server.Prefixes.Add("http://127.0.0.1:" + port + "/observer-mode/rest/consumer/");
server.Start();
} catch {
try { AddAddress("http://127.0.0.1:" + port + "/"); } catch { return; }
server = new HttpListener();
server.Prefixes.Add("http://127.0.0.1:" + port + "/observer-mode/rest/consumer/");
server.Start();
}
new Thread(this.Stopper) { IsBackground = true, Name = "Server Stopper" }.Start();
new Thread(() => {
Logger.WriteLine("Starting Spectator Server [ID: {0}]... ".Format(replay.GameId));
try {
while (alive) { Handle(server.GetContext()); }
} catch { }
server.Close();
Logger.WriteLine("Closing Spectator Server");
}) { IsBackground = true, Name = "ServerHandler" }.Start();
var dir = new System.IO.DirectoryInfo(@"C:\Riot Games\League of Legends\RADS\"
+ @"solutions\lol_game_client_sln\releases\");
var versions = dir.EnumerateDirectories().ToList();
versions.Sort((a, b) => b.Name.CompareTo(a.Name));
ProcessStartInfo info = new ProcessStartInfo(versions[0].FullName + @"\deploy\League of Legends.exe",
String.Join(" ", SpectateArgs).Format(replay.MetaData["encryptionKey"], replay.GameId));
info.WorkingDirectory = versions[0].FullName + @"\deploy";
Process.Start(info);
}
示例4: 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");
}
示例5: CheckPort
private bool CheckPort(int? port)
{
var listener = new HttpListener();
try
{
listener.Prefixes.Add("http://+:{0}/".FormatFrom(port));
listener.Start();
return true;
}
catch (Exception ex)
{
_log.WarnFormat("Failed to access HTTP port {0}: {1}", port, ex.Summary());
return false;
}
finally
{
try
{
listener.Close();
}
catch (Exception ex)
{
_log.WarnFormat("Failed to close HTTP port {0}: {1}", port, ex.Summary());
}
}
}
示例6: ReceiveCodeAsync
public async Task<AuthorizationCodeResponse> ReceiveCodeAsync(string authorizationUrl,
CancellationToken taskCancellationToken)
{
using (var listener = new HttpListener())
{
listener.Prefixes.Add(CallbackUrl);
try
{
listener.Start();
var p = Process.Start(authorizationUrl);
// Wait to get the authorization code response.
var context = await listener.GetContextAsync().ConfigureAwait(false);
var coll = context.Request.QueryString;
// Write a "close" response.
using (var writer = new StreamWriter(context.Response.OutputStream))
{
writer.WriteLine(ClosePageResponse);
writer.Flush();
}
context.Response.OutputStream.Close();
// Create a new response URL with a dictionary that contains all the response query parameters.
return new AuthorizationCodeResponse(coll.AllKeys.ToDictionary(k => k, k => coll[(string) k]));
}
finally
{
listener.Close();
}
}
}
示例7: BasicRoundTrip
public void BasicRoundTrip()
{
var serializer = new JsonCommonSerializer();
var server = new HttpListener();
server.Prefixes.Add("http://localhost:20000/");
server.Start();
var serverTransport = server.GenerateTransportSource();
var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
serverRouter.AddService<IMyService>(new MyService());
var client = new ClientWebSocket();
client.Options.SetBuffer(8192, 8192);
var clientTransport = client.GenerateTransportSource();
var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
var proxy = clientRouter.AddInterface<IMyService>();
client.ConnectAsync(new Uri("ws://localhost:20000/"), CancellationToken.None).Wait();
var result = proxy.Add(3, 4).Result;
Assert.Equal(7, result);
clientRouter.Dispose();
clientTransport.Dispose();
client.Dispose();
serverRouter.Dispose();
serverTransport.Dispose();
server.Stop();
server.Close();
}
示例8: KillAnyExistingListeners
private void KillAnyExistingListeners() {
if (ActiveListeners.Count != 0) {
var staleListener = new HttpListener();
staleListener.Prefixes.Add(ActiveListeners[0]);
staleListener.Stop();
staleListener.Close();
ActiveListeners.Clear();
}
ActiveListeners.Add(ListenerAddress);
}
示例9: HttpEndpointDoesNotThrowIfPortIsOccupied
public void HttpEndpointDoesNotThrowIfPortIsOccupied()
{
using (var listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/");
listener.Start();
Metric.Config.WithHttpEndpoint("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/");
listener.Close();
}
}
示例10: Main
static void Main(string[] args)
{
HttpListener httpListner = new HttpListener();
httpListner.Prefixes.Add("http://*:8080/");
httpListner.Start();
Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));
Console.ReadKey();
httpListner.Close();
}
示例11: WaitFor
public RequestResult WaitFor(Action request, int timeout)
{
var result = new RequestResult();
using (var listener = new HttpListener())
{
var server = listener;
Action test = () =>
{
server.Prefixes.Add(_listenUri);
server.Start();
request();
var context = server.GetContext();
result.ContentType = context.Request.ContentType;
result.HttpMethod = context.Request.HttpMethod;
try
{
using (var reader = new StreamReader(context.Request.InputStream))
{
var body = reader.ReadToEnd();
var serializer = new JavaScriptSerializer();
result.Json = serializer.Deserialize<Dictionary<string, object>>(body);
}
context.Response.StatusCode = 200;
}
catch
{
context.Response.StatusCode = 500;
}
finally
{
context.Response.Close();
}
};
result.TimedOut = Wait(test, timeout);
listener.Stop();
listener.Close();
}
return result;
}
示例12: HttpEndportLogsAnErrorIfPortIsOccupied
public void HttpEndportLogsAnErrorIfPortIsOccupied()
{
using (var listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/");
listener.Start();
var loggedAnError = false;
using (var config = Metric.Config)
{
config.WithErrorHandler((exception, s) => { loggedAnError = true; }, true);
config.WithErrorHandler((exception) => { loggedAnError = true; }, true);
config.WithHttpEndpoint("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/");
}
Assert.True(loggedAnError);
listener.Close();
}
}
示例13: GetNewHttpListenerAddress
private string GetNewHttpListenerAddress() {
string listenerAddress;
while (true) {
var listener = new HttpListener();
var randomPortNumber = Random.Next(1025, 65535);
listenerAddress = string.Format("http://localhost:{0}/", randomPortNumber);
listener.Prefixes.Add(listenerAddress);
try {
listener.Start();
listener.Stop();
listener.Close();
}
catch {
continue;
}
break;
}
return listenerAddress;
}
示例14: startListner
public void startListner()
{
stirixListener = stirixSingleton.Instance;
stirixListener.Prefixes.Add("http://*:9090/");
stirixListener.Start();
IAsyncResult result;
Boolean error=false;
while(!error){
try{
result = stirixListener.BeginGetContext(new AsyncCallback(getData), stirixListener);
Console.WriteLine("Waiting for request to be processed asyncronously.");
}
catch(Exception e)
{
error=true;
}
}
// result.AsyncWaitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
stirixListener.Close();
}
示例15: InitializeAsync
public async Task InitializeAsync(CancellationToken ct) {
await TaskUtilities.SwitchToBackgroundThread();
Random r = new Random();
// if remote port is between 10000 and 32000, select a port in the same range.
// R Help uses ports in that range.
int localPortMin = (RemotePort >= 10000 && RemotePort <= 32000) ? 10000 : 49152;
int localPortMax = (RemotePort >= 10000 && RemotePort <= 32000) ? 32000 : 65535;
_console.WriteLine(Resources.Info_RemoteWebServerStarting.FormatInvariant(_name));
while (true) {
ct.ThrowIfCancellationRequested();
_listener = new HttpListener();
LocalPort = r.Next(localPortMin, localPortMax);
_listener.Prefixes.Add(Invariant($"http://{LocalHost}:{LocalPort}/"));
try {
_listener.Start();
} catch (HttpListenerException) {
_listener.Close();
continue;
} catch (ObjectDisposedException) {
// Socket got closed
await Log.WriteLineAsync(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name));
_console.WriteLine(Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name));
throw new OperationCanceledException();
}
break;
}
try {
await Log.WriteLineAsync(LogVerbosity.Minimal, MessageCategory.General, Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort));
_console.WriteLine(Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort));
_console.WriteLine(Resources.Info_RemoteWebServerDetails.FormatInvariant(Environment.MachineName, LocalHost, LocalPort, _name, RemoteHost, RemotePort));
} catch {
}
}