-
Notifications
You must be signed in to change notification settings - Fork 0
/
Webserver.cs
102 lines (90 loc) · 3.21 KB
/
Webserver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;
namespace Diamond_Chat_Bot
{
public class Webserver
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public Webserver(IReadOnlyCollection<string> prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
{
throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
}
// URI prefixes are required eg: "http://localhost:8080/test/"
if (prefixes == null || prefixes.Count == 0)
{
throw new ArgumentException("URI prefixes are required");
}
if (method == null)
{
throw new ArgumentException("responder method required");
}
foreach (var s in prefixes)
{
_listener.Prefixes.Add(s);
}
_responderMethod = method;
_listener.Start();
}
public Webserver(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method)
{
}
public void Run()
{
ThreadPool.QueueUserWorkItem(o =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem(c =>
{
var ctx = c as HttpListenerContext;
try
{
if (ctx == null)
{
return;
}
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch
{
// ignored
}
finally
{
// always close the stream
if (ctx != null)
{
ctx.Response.OutputStream.Close();
}
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
// ignored
}
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}