2012-07-12 06:55:27 +00:00
|
|
|
using System;
|
|
|
|
using System.Net;
|
|
|
|
using System.Reactive.Linq;
|
|
|
|
|
2012-07-21 18:39:47 +00:00
|
|
|
namespace MediaBrowser.Common.Net
|
2012-07-12 06:55:27 +00:00
|
|
|
{
|
2012-08-10 13:07:58 +00:00
|
|
|
public class HttpServer : IObservable<HttpListenerContext>, IDisposable
|
2012-07-12 06:55:27 +00:00
|
|
|
{
|
2012-09-11 19:37:14 +00:00
|
|
|
private readonly HttpListener _listener;
|
|
|
|
private readonly IObservable<HttpListenerContext> _stream;
|
2012-07-12 06:55:27 +00:00
|
|
|
|
|
|
|
public HttpServer(string url)
|
|
|
|
{
|
2012-09-11 19:37:14 +00:00
|
|
|
_listener = new HttpListener();
|
|
|
|
_listener.Prefixes.Add(url);
|
|
|
|
_listener.Start();
|
|
|
|
_stream = ObservableHttpContext();
|
2012-07-12 06:55:27 +00:00
|
|
|
}
|
|
|
|
|
2012-08-10 13:07:58 +00:00
|
|
|
private IObservable<HttpListenerContext> ObservableHttpContext()
|
2012-07-12 06:55:27 +00:00
|
|
|
{
|
2012-08-10 13:07:58 +00:00
|
|
|
return Observable.Create<HttpListenerContext>(obs =>
|
2012-09-11 19:37:14 +00:00
|
|
|
Observable.FromAsync(() => _listener.GetContextAsync())
|
2012-07-12 06:55:27 +00:00
|
|
|
.Subscribe(obs))
|
|
|
|
.Repeat()
|
|
|
|
.Retry()
|
|
|
|
.Publish()
|
|
|
|
.RefCount();
|
|
|
|
}
|
|
|
|
public void Dispose()
|
|
|
|
{
|
2012-09-11 19:37:14 +00:00
|
|
|
_listener.Stop();
|
2012-07-12 06:55:27 +00:00
|
|
|
}
|
|
|
|
|
2012-08-10 13:07:58 +00:00
|
|
|
public IDisposable Subscribe(IObserver<HttpListenerContext> observer)
|
2012-07-12 06:55:27 +00:00
|
|
|
{
|
2012-09-11 19:37:14 +00:00
|
|
|
return _stream.Subscribe(observer);
|
2012-07-12 06:55:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|