本文整理汇总了C#中System.Net.HttpListener.Abort方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.Abort方法的具体用法?C# HttpListener.Abort怎么用?C# HttpListener.Abort使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpListener
的用法示例。
在下文中一共展示了HttpListener.Abort方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BeginListeningAsync
public async Task BeginListeningAsync (CancellationToken token)
{
var listener = new HttpListener ();
listener.Prefixes.Add (string.Format ("http://*:{0}/", ListenPort));
try {
using (token.Register (() => listener.Abort ()))
using (listener) {
listener.Start ();
while (!token.IsCancellationRequested) {
var context = await listener.GetContextAsync ().ConfigureAwait (false);
ContextReceived (Catalog, context, token);
}
}
} catch (ObjectDisposedException ex) {
if (!token.IsCancellationRequested) {
LoggingService.LogError (ex, "Unexpected ObjectDisposedException in BeginListeningAsync");
throw;
}
} catch (OperationCanceledException) {
// We cancelled successfully
} catch (Exception ex) {
LoggingService.LogError (ex, "Unhandled exception in BeginListeningAsync");
}
}
示例2: Main
private static void Main(string[] args)
{
Console.WriteLine("Begin Loading ");
big.loadSFIO(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\bigfile");
Console.WriteLine("LOADED maxFile = " + big.maxSeq);
using (listener = new HttpListener())
{
listener.Prefixes.Add("http://*:8080/");
listener.Start();
for (int count = 0; count < maxRequestHandlers; count++)
{
listener.BeginGetContext(RequestHandler, "RequestHandler_" +
Interlocked.Increment(ref requestHandlerID));
}
Console.WriteLine("HTTP Server running on 8080 port, press enter to abort");
Console.ReadLine();
listener.Stop();
listener.Abort();
}
}
示例3: RunHttpServerThread
private void RunHttpServerThread()
{
this._httpListenThread = new Thread(new ThreadStart(()=>
{
HttpListener httpListener = new HttpListener();
try
{
this._httpImplanter.MakeHttpPrefix(httpListener);
httpListener.Start();
}
catch (Exception var_1_1F)
{
Logger.Exit("无法启动服务器监听,请检查网络环境。");
}
this._httpImplanter.Start();
IAsyncResult asyncResult = null;
while (!this._terminated)
{
while (asyncResult == null || asyncResult.IsCompleted)
{
asyncResult = httpListener.BeginGetContext(new AsyncCallback(this.ProcessHttpRequest), httpListener);
}
this._ready = true;
Thread.Sleep(10);
}
httpListener.Stop();
httpListener.Abort();
httpListener.Close();
this._httpImplanter.Stop();
}));
this._httpListenThread.IsBackground = true;
this._httpListenThread.Start();
}
示例4: AbortWhileBegin
public void AbortWhileBegin ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:9001/abortwhilebegin/");
listener.Start ();
CallMe cm = new CallMe ();
listener.BeginGetContext (cm.Callback, listener);
listener.Abort ();
if (false == cm.Event.WaitOne (3000, false))
Assert.Fail ("This should not time out.");
Assert.IsNotNull (cm.Error);
Assert.AreEqual (typeof (ObjectDisposedException), cm.Error.GetType (), "Exception type");
cm.Dispose ();
}
示例5: AbortTwice
public void AbortTwice ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://localhost:7777/hola/");
listener.Start ();
listener.Abort ();
listener.Abort ();
}
示例6: AbortBeforeStart
public void AbortBeforeStart ()
{
HttpListener listener = new HttpListener ();
listener.Abort ();
}
示例7: AbortTwice
public void AbortTwice ()
{
if (!CanOpenPort (port))
Assert.Ignore ("port");
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://localhost:" + port + "/hola/");
listener.Start ();
listener.Abort ();
listener.Abort ();
}
示例8: StartListening
private void StartListening()
{
HttpListener httpListener = null;
try
{
httpListener = new HttpListener("http", _port);
httpListener.Start();
while (true)
{
var context = httpListener.GetContext();
new Thread(() =>
{
var request = context.Request;
var response = context.Response;
var requestName = request.HttpMethod + " " + request.RawUrl;
try
{
// Validate credentials, if enabled
if (_credentialsValidator != null && !_credentialsValidator.Validate(request.Credentials))
{
response.Headers.Add("WWW-Authenticate", "Basic realm=\"" + _credentialsValidator.Realm + "\"");
string message = "Unauthorized";
if (request.Credentials != null)
message += " username=" + request.Credentials.UserName;
SendResponseWithError(response, HttpStatusCode.Unauthorized, message);
return;
}
Logger.Instance.LogInfo("Request " + requestName);
if (!_restApi.Handle(context))
{
SendResponseWithError(response, HttpStatusCode.NotFound, "No handler for " + requestName);
}
}
catch (RestException rex)
{
SendResponseWithError(response, rex.Status, "Error handling " + requestName + ": " + rex.Message);
}
catch (Exception ex)
{
SendResponseWithError(response, HttpStatusCode.InternalServerError, "Exception handling " + requestName + ": " + ex.Message + " at " + ex.StackTrace);
}
finally
{
context.Close();
}
}).Start();
}
}
catch
{
if (httpListener != null)
httpListener.Abort();
}
}
示例9: Start
protected void Start(Action action, Func<IWebDriver, bool> preExtraTest = null, Func<IWebDriver, bool> postExtraTest = null, TimeSpan? timeout = null) {
if (timeout == null) {
timeout = TimeSpan.FromSeconds(1000);
}
var method = CecilHelper.GetMethod(action.Method);
var jsResult = Js.CreateFrom(method, this.Verbose, true);
var js = jsResult.Js;
if (this.Verbose) {
Console.WriteLine(js);
}
var completeHtml = this.MakeHtml(js);
using (var http = new HttpListener()) {
http.Prefixes.Add("http://localhost:7890/");
http.Start();
AsyncCallback cb = null;
cb = asyncState => {
if (!http.IsListening) {
return;
}
HttpListenerContext context;
try {
context = http.EndGetContext(asyncState);
} catch (HttpListenerException) {
return;
} catch (ObjectDisposedException) {
return;
}
using (var response = context.Response) {
var output = response.OutputStream;
var path = context.Request.Url.AbsolutePath;
string responseString;
if (path == "/") {
responseString = completeHtml;
} else {
var request = context.Request;
using (var ms = new MemoryStream()) {
request.InputStream.CopyTo(ms);
var bytes = ms.ToArray();
Func<byte[], string> fn;
urls.TryGetValue(path, out fn);
responseString = fn != null ? fn(bytes) : "";
}
}
var bHtml = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = bHtml.LongLength;
output.Write(bHtml, 0, bHtml.Length);
}
http.BeginGetContext(cb, null);
};
http.BeginGetContext(cb, null);
//var usingNamespace = NamespaceSetup.Chrome != null;
//var chrome = usingNamespace ? NamespaceSetup.Chrome : new ChromeDriver();
using (var chrome = NamespaceSetup.ChromeService != null ?
new RemoteWebDriver(NamespaceSetup.ChromeService.ServiceUrl, DesiredCapabilities.Chrome()) :
new ChromeDriver()) {
try {
this.jsonTypeMap = jsResult.TypeMap;
chrome.Manage().Timeouts().ImplicitlyWait(timeout.Value);
chrome.Url = "http://localhost:7890/";
bool isPass = true;
if (preExtraTest != null) {
isPass = preExtraTest(chrome);
}
if (isPass) {
IWebElement done;
string doneText = "";
try {
done = chrome.FindElementById("__done__");
doneText = done.Text;
} catch (NoSuchElementException) {
isPass = false;
} catch {
isPass = false;
}
isPass = doneText == "pass";
if (!isPass) {
if (doneText.StartsWith("ex:")) {
throw new Exception(doneText.Substring(3));
}
if (doneText.StartsWith("onerror:")) {
throw new Exception(doneText.Substring(8));
}
}
if (isPass && postExtraTest != null) {
isPass = postExtraTest(chrome);
}
}
Assert.That(isPass, Is.True);
} finally {
//if (!usingNamespace) {
chrome.Quit();
chrome.Dispose();
//}
this.jsonTypeMap = null;
}
}
http.Abort();
}
}
示例10: AuthorizeAction
public static void AuthorizeAction (NSWindow window, String serverURL) {
if (String.IsNullOrEmpty (serverURL) || String.IsNullOrWhiteSpace (serverURL)) {
NSAlert alert = new NSAlert () {
MessageText = "Incorrect URL",
InformativeText = "The Sync URL cannot be empty",
AlertStyle = NSAlertStyle.Warning
};
alert.AddButton ("OK");
alert.BeginSheet (window,
null,
null,
IntPtr.Zero);
//SyncURL.StringValue = "";
return;
} else {
if (!serverURL.EndsWith ("/"))
serverURL += "/";
}
HttpListener listener = new HttpListener ();
string callbackURL = "http://localhost:9001/";
listener.Prefixes.Add (callbackURL);
listener.Start ();
var callback_delegate = new OAuthAuthorizationCallback ( url => {
Process.Start (url);
// wait (block) until the HttpListener has received a request
var context = listener.GetContext ();
// if we reach here the authentication has most likely been successfull and we have the
// oauth_identifier in the request url query as a query parameter
var request_url = context.Request.Url;
string oauth_verifier = System.Web.HttpUtility.ParseQueryString (request_url.Query).Get("oauth_verifier");
if (string.IsNullOrEmpty (oauth_verifier)) {
// authentication failed or error
context.Response.StatusCode = 500;
context.Response.StatusDescription = "Error";
context.Response.Close();
throw new ArgumentException ("oauth_verifier");
} else {
// authentication successfull
context.Response.StatusCode = 200;
using (var writer = new StreamWriter (context.Response.OutputStream)) {
writer.WriteLine("<h1>Authorization successfull!</h1>Go back to the Tomboy application window.");
}
context.Response.Close();
return oauth_verifier;
}
});
try{
//FIXME: see http://mono-project.com/UsingTrustedRootsRespectfully for SSL warning
ServicePointManager.CertificatePolicy = new DummyCertificateManager ();
IOAuthToken access_token = WebSyncServer.PerformTokenExchange (serverURL, callbackURL, callback_delegate);
AppDelegate.settings.webSyncURL = serverURL;
AppDelegate.settings.token = access_token.Token;
AppDelegate.settings.secret = access_token.Secret;
SettingsSync.Write (AppDelegate.settings);
Console.WriteLine ("Received token {0} with secret key {1}",access_token.Token, access_token.Secret);
listener.Stop ();
NSAlert success = new NSAlert () {
MessageText = "Authentication Successful",
InformativeText = "The authentication with the server has been successful. You can sync with the web server now.",
AlertStyle = NSAlertStyle.Informational
};
success.AddButton ("OK");
success.BeginSheet (window,
window,
null,
IntPtr.Zero);
return;
} catch (Exception ex) {
if (ex is WebException || ex is System.Runtime.Serialization.SerializationException) {
NSAlert alert = new NSAlert () {
MessageText = "Incorrect URL",
InformativeText = "The URL entered " + serverURL + " is not valid for syncing",
AlertStyle = NSAlertStyle.Warning
};
alert.AddButton ("OK");
alert.BeginSheet (window,
null,
null,
IntPtr.Zero);
listener.Abort ();
return;
//.........这里部分代码省略.........
示例11: OnOpen
//.........这里部分代码省略.........
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnrecognizedHostNameComparisonMode, HostNameComparisonMode.ToString())));
}
string path = ListenUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
if (!path.StartsWith("/", StringComparison.Ordinal))
path = "/" + path;
if (!path.EndsWith("/", StringComparison.Ordinal))
path = path + "/";
string httpListenUrl = string.Concat(Scheme, "://", host, ":", ListenUri.Port, path);
listener.UnsafeConnectionNtlmAuthentication = this.unsafeConnectionNtlmAuthentication;
listener.AuthenticationSchemeSelectorDelegate =
new AuthenticationSchemeSelector(SelectAuthenticationScheme);
if (ExtendedProtectionPolicy.OSSupportsExtendedProtection)
{
//This API will throw if on an unsupported platform.
listener.ExtendedProtectionSelectorDelegate =
new HttpListener.ExtendedProtectionSelector(SelectExtendedProtectionPolicy);
}
if (this.Realm != null)
{
listener.Realm = this.Realm;
}
bool success = false;
try
{
listener.Prefixes.Add(httpListenUrl);
listener.Start();
bool startedListening = false;
try
{
if (Thread.CurrentThread.IsThreadPoolThread)
{
StartListening();
}
else
{
// If we're not on a threadpool thread, then we need to post a callback to start our accepting loop
// Otherwise if the calling thread aborts then the async I/O will get inadvertantly cancelled
listenStartedEvent = new ManualResetEvent(false);
ActionItem.Schedule(OnListening, null);
listenStartedEvent.WaitOne();
listenStartedEvent.Close();
listenStartedEvent = null;
if (listenStartedException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(listenStartedException);
}
}
startedListening = true;
}
finally
{
if (!startedListening)
{
listener.Stop();
}
}
success = true;
}
catch (HttpListenerException listenerException)
{
switch (listenerException.NativeErrorCode)
{
case UnsafeNativeMethods.ERROR_ALREADY_EXISTS:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAlreadyInUseException(SR.GetString(SR.HttpRegistrationAlreadyExists, httpListenUrl), listenerException));
case UnsafeNativeMethods.ERROR_SHARING_VIOLATION:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAlreadyInUseException(SR.GetString(SR.HttpRegistrationPortInUse, httpListenUrl, ListenUri.Port), listenerException));
case UnsafeNativeMethods.ERROR_ACCESS_DENIED:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAccessDeniedException(SR.GetString(SR.HttpRegistrationAccessDenied, httpListenUrl), listenerException));
case UnsafeNativeMethods.ERROR_ALLOTTED_SPACE_EXCEEDED:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.HttpRegistrationLimitExceeded, httpListenUrl), listenerException));
case UnsafeNativeMethods.ERROR_INVALID_PARAMETER:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.HttpInvalidListenURI, ListenUri.OriginalString), listenerException));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
HttpChannelUtilities.CreateCommunicationException(listenerException));
}
}
finally
{
if (!success)
{
listener.Abort();
}
}
}
示例12: ListenForRequests
/// <summary>
/// Start listening to requests from clients.
/// </summary>
public void ListenForRequests()
{
Start:
try {
http = new HttpListener();
http.Prefixes.Add( "http://+:" + port.ToString() + "/" );
http.Start();
HttpListenerContext hlc;
while ( true ) {
hlc = http.GetContext(); //Wait for request
//Check if we have a thread to handle the request:
bool found = false;
lock ( threadPool ) {
for ( int i = 0; i < MaxThreads; i++ ) {
if ( threadPool[i] == null ) {
ThreadHttpContextPair thcp = new ThreadHttpContextPair();
thcp.hlc = hlc;
thcp.id = i;
threadPool[i] = new Thread( new ParameterizedThreadStart( this.HandleRequest ) );
threadPool[i].Start( thcp );
found = true;
break;
}
}
if ( !found ) {
hlc.Response.StatusCode = 500;
hlc.Response.Close();
}
}
}
}
catch ( ThreadInterruptedException ) {
for ( int i = 0; i < MaxThreads; i++ ) {
if ( threadPool[i] != null ) {
threadPool[i].Abort();
threadPool[i].Join();
}
}
}
catch ( ThreadAbortException ) {
for ( int i = 0; i < MaxThreads; i++ ) {
if ( threadPool[i] != null ) {
threadPool[i].Abort();
threadPool[i].Join();
}
}
}
catch ( HttpListenerException ) {
try {
http.Stop();
http.Abort();
}
catch ( ObjectDisposedException ) {
//Do nothing. We just had to make sure it was dead. This bug comes back every once in a while. Dunno why.
}
goto Start;
}
}
示例13: Webserver
static async void Webserver(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
var listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
Console.WriteLine("Prefix :{0}",s);
}
listener.Start();
Console.WriteLine("{0}=>Listening...", listener);
while (listener.IsListening)
{
// Note: The GetContext method blocks while waiting for a request.
var context = await listener.GetContextAsync();
var request = context.Request;
var response = context.Response;
//Console.WriteLine("{0} >> {1} >> {2}", request.RemoteEndPoint, request.HttpMethod, request.RawUrl);
String req = di.FullName + (request.RawUrl).Split(new char[] {'?'},StringSplitOptions.RemoveEmptyEntries).First();
switch (req)
{
case "/":
await ServeRedisAsync(new FileInfo(req + "index.html"), response);
break;
case "/exit":
response.Close();
listener.Abort();
break;
default:
await ServeRedisAsync(new FileInfo(req), response);
break;
}
}
listener.Stop();
//Console.WriteLine("REDIS connection {0} opened.", redis.Host);
redis.Close(true);
redis.Error -= redis_Error;
redis.Dispose();
}