1 |
// Share |
2 |
// |
3 |
// Douglas Thrift |
4 |
// |
5 |
// $Id$ |
6 |
|
7 |
using System; |
8 |
using System.IO; |
9 |
using System.Net; |
10 |
using System.Text; |
11 |
using System.Threading; |
12 |
|
13 |
public class Share |
14 |
{ |
15 |
public string name { get { return name_; } } |
16 |
|
17 |
public Share(string path, MediaFolder folder) |
18 |
{ |
19 |
name_ = String.Format("{0:x}", path.GetHashCode()); |
20 |
folder_ = folder; |
21 |
listener.IgnoreWriteExceptions = true; |
22 |
|
23 |
listener.Prefixes.Add(String.Format("http://+:6996/{0}/", name_)); |
24 |
listener.Start(); |
25 |
|
26 |
thread = new Thread(new ThreadStart(Serve)); |
27 |
|
28 |
thread.Start(); |
29 |
} |
30 |
|
31 |
~Share() |
32 |
{ |
33 |
Stop(); |
34 |
} |
35 |
|
36 |
public void Stop() |
37 |
{ |
38 |
listener.Stop(); |
39 |
thread.Join(); |
40 |
} |
41 |
|
42 |
private string name_; |
43 |
private MediaFolder folder_; |
44 |
private HttpListener listener = new HttpListener(); |
45 |
private Thread thread; |
46 |
|
47 |
private void Serve() |
48 |
{ |
49 |
while (listener.IsListening) |
50 |
ThreadPool.QueueUserWorkItem(new WaitCallback(Serve), listener.GetContext()); |
51 |
} |
52 |
|
53 |
private void Serve(object context) |
54 |
{ |
55 |
HttpListenerContext context_ = (HttpListenerContext)context; |
56 |
HttpListenerRequest request = context_.Request; |
57 |
HttpListenerResponse response = context_.Response; |
58 |
|
59 |
Console.WriteLine(request.Url.LocalPath); |
60 |
|
61 |
char[] slash = { '/' }; |
62 |
string[] path = request.Url.LocalPath.Split(slash, 2, StringSplitOptions.RemoveEmptyEntries); |
63 |
Stream stream; |
64 |
|
65 |
if (path.Length == 2 && (response.ContentLength64 = folder_.Get(path[1], out stream)) != -1) |
66 |
{ |
67 |
byte[] buffer = new byte[2097152]; |
68 |
int count; |
69 |
|
70 |
while ((count = stream.Read(buffer, 0, buffer.Length)) != 0) |
71 |
response.OutputStream.Write(buffer, 0, count); |
72 |
|
73 |
stream.Close(); |
74 |
} |
75 |
else |
76 |
// XXX: I wonder if they'll make this thing an enum |
77 |
response.StatusCode = (int)HttpStatusCode.NotFound; |
78 |
|
79 |
response.OutputStream.Close(); |
80 |
response.Close(); |
81 |
} |
82 |
} |