// Share // // Douglas Thrift // // $Id$ using System; using System.IO; using System.Net; using System.Text; using System.Threading; public class Share { public string name { get { return name_; } } public Share(string path, MediaFolder folder) { name_ = String.Format("{0:x}", path.GetHashCode()); folder_ = folder; listener.IgnoreWriteExceptions = true; listener.Prefixes.Add(String.Format("http://+:6996/{0}/", name_)); listener.Start(); thread = new Thread(new ThreadStart(Serve)); thread.Start(); } ~Share() { Stop(); } public void Stop() { listener.Stop(); thread.Join(); } private string name_; private MediaFolder folder_; private HttpListener listener = new HttpListener(); private Thread thread; private void Serve() { while (listener.IsListening) ThreadPool.QueueUserWorkItem(new WaitCallback(Serve), listener.GetContext()); } private void Serve(object context) { HttpListenerContext context_ = (HttpListenerContext)context; HttpListenerRequest request = context_.Request; HttpListenerResponse response = context_.Response; Console.WriteLine(request.Url.LocalPath); char[] slash = { '/' }; string[] path = request.Url.LocalPath.Split(slash, 2, StringSplitOptions.RemoveEmptyEntries); Stream stream; if (path.Length == 2 && (response.ContentLength64 = folder_.Get(path[1], out stream)) != -1) { byte[] buffer = new byte[2097152]; int count; while ((count = stream.Read(buffer, 0, buffer.Length)) != 0) response.OutputStream.Write(buffer, 0, count); stream.Close(); } else // XXX: I wonder if they'll make this thing an enum response.StatusCode = (int)HttpStatusCode.NotFound; response.OutputStream.Close(); response.Close(); } }